
Frontend web security interview questions test whether you can reason about browser boundaries. You should be able to explain where untrusted data enters, where it is rendered, which cookies are sent automatically, which origins can read responses, and which checks must happen on the server.
The best answers are scenario-based. A definition of XSS, CSRF, or CORS is only the first step. Interviewers want to know what you would inspect, what you would change, what tradeoff you would accept, and how you would verify that the fix works.
For technical accuracy, use official references as your source of truth: the OWASP Top 10 for broad application risk, the OWASP XSS Prevention Cheat Sheet, the OWASP CSRF Prevention Cheat Sheet, MDN Web Security, MDN CORS, MDN CSP, MDN Set-Cookie, and MDN postMessage. Interview-question lists are useful for prompts; official docs are better for the actual answer.
Most frontend security answers become clearer if you first name the boundary. Do not start with "make it secure." Start with what the browser, frontend, API, or server is allowed to trust.
| Boundary | Interviewer is testing | Good answer should include |
|---|---|---|
| User content to DOM | XSS, output context, safe sinks | Source, sink, execution context, escaping, sanitization when rich HTML is allowed |
| Other site to your API | CSRF, cookies, request side effects | Automatic cookie sending, server-side token or origin validation, no side effects on GET |
| Other origin to your frontend | CORS, same-origin policy | Scheme/host/port origin, preflight, credential rules, CORS is not auth |
| Browser storage to attacker script | Token theft, session handling | XSS risk, cookie attributes, refresh flow, short lifetimes, server enforcement |
| Third-party code to your page | Supply-chain and script risk | Data access, CSP, route scoping, SRI where possible, dependency review |
| UI permission to API permission | Authorization boundary | Frontend UX checks versus server-side enforcement, 401 and 403 behavior |
XSS happens when untrusted data is interpreted as executable code in a page. In frontend interviews, connect the answer to the exact rendering path: where the data came from, which DOM sink receives it, and which parsing context the browser uses.
A good answer:
innerHTML when the content should be text.Common mistake: saying React, Vue, or Angular makes XSS impossible. Framework escaping helps with text rendering, but unsafe HTML APIs, unsafe URL handling, third-party scripts, and server-rendered templates can still create XSS risk.
React escapes text by default, but React does not remove every XSS path. XSS can still happen through dangerouslySetInnerHTML, untrusted markdown or HTML renderers, direct DOM manipulation through refs, dangerous URL schemes passed to DOM APIs, third-party scripts, and HTML created outside React.
Interview-ready answer:
"I would first check whether the value is rendered as text or HTML. If it is plain text, React's escaping is usually the right path. If the product needs rich text, I would sanitize with an allowlist, validate link protocols, avoid dangerous DOM sinks, and add tests for stored payloads. I would also check CSP and any third-party scripts on that page."
Validation checks whether input has the expected shape. Encoding changes output so the browser treats it as data in the current context. Sanitization removes or rewrites unsafe parts of content that is intentionally allowed to contain markup.
Example:
https:// or an allowed app route.Common mistake: saying "sanitize all input" as a universal answer. For plain text, the safer answer is usually to render it as text. Sanitization is for cases where the product intentionally allows rich content.
A safe sink treats data as text or a controlled value instead of executable markup. Examples include textContent, form value, and framework text interpolation when used normally.
The caveat matters: a sink is safe only for the right context. Hardcoded safe attribute names are different from dynamically choosing an attribute name. A URL attribute is different from normal text. An interviewer will often follow up with innerHTML, href, markdown, or rich-text examples to check whether the answer survives detail.
CSRF tricks a logged-in browser into sending a state-changing request that includes the user's cookies. The attacker may not be able to read the response, but the server may still receive and process the request.
Defenses include:
SameSite cookies as defense-in-depth.Origin or Referer checks for sensitive state-changing requests.GET.Common mistake: thinking HttpOnly prevents CSRF. HttpOnly prevents JavaScript from reading a cookie; it does not stop the browser from automatically sending that cookie.
HttpOnly, Secure, and SameSite protect?Cookie attributes reduce different risks, so name the risk instead of calling a cookie "secure."
| Attribute | Browser behavior | Does not protect against |
|---|---|---|
HttpOnly | Prevents JavaScript from reading the cookie through document.cookie | Requests caused by injected script or automatic cookie sending |
Secure | Sends the cookie only over secure connections, except for defined localhost handling | XSS, CSRF, or broken authorization |
SameSite=Lax or Strict | Restricts when the cookie accompanies cross-site requests | Every CSRF case or same-site attacks |
SameSite=None; Secure | Allows cross-site cookie use while requiring secure transport | CSRF, misconfigured CORS, or missing authorization |
Also mention that cookie Path is not an access-control boundary. It controls when the browser sends a cookie; it should not be treated as protection from unauthorized reading.
CORS is a browser-enforced mechanism that controls whether frontend JavaScript from one origin may read a response from another origin. An origin is the scheme, host, and port.
Good answer:
OPTIONS request.Access-Control-Allow-Origin: *.Common mistake: debugging React code when the actual problem is the API's CORS headers. If a request works in Postman but fails in the browser, check browser security rules before rewriting components.
There is no universal answer. The right storage choice depends on the auth model, threat model, and product constraints.
| Option | Useful when | Main risk |
|---|---|---|
| HttpOnly Secure cookie | You want to reduce token theft by JavaScript | Needs CSRF defenses for cookie-auth flows |
| Memory | You want less persistence after refresh or XSS cleanup | Harder refresh flow and tab coordination |
sessionStorage | You need tab-scoped persistence | Readable by injected scripts in that tab |
localStorage | Simpler persistence for bearer-token apps | Readable by injected scripts and often overused for long-lived tokens |
An interview-ready answer names the tradeoff: cookies reduce JavaScript token theft but require CSRF thinking; browser storage can simplify bearer-token flows but makes XSS theft more damaging. Short lifetimes, rotation, least privilege, refresh strategy, and server-side revocation matter more than declaring one storage location always safe.
CSP lets a site restrict which resources a page can load and which scripts can execute. It can reduce XSS impact by blocking inline scripts, javascript: URLs, unexpected script sources, and dangerous APIs such as eval() when the policy is strict enough.
A good answer:
unsafe-inline unless there is a temporary migration reason.Content-Security-Policy-Report-Only before enforcing a risky policy.Common mistake: adding a loose policy with unsafe-inline and many wildcard sources, then treating the page as protected.
postMessage be used safely?window.postMessage lets a window communicate with another window it references, such as a popup, parent, or iframe, even across origins. Workers and MessagePort objects have related messaging APIs, but targetOrigin and event.origin checks here apply specifically to window-to-window messaging.
Use a specific targetOrigin when sending. On receive, validate event.origin, check event.source when you expect one particular window, validate the message shape, and avoid sending secrets through generic message channels. If the message changes auth state, payment state, or account data, treat the receiver like any other trusted integration and document the expected source, origin, and schema.
Common mistake: using * for sensitive messages or trusting every message event because it arrived in the browser.
Frontend checks are useful for UX and accidental misuse, but they are not authorization. The frontend can hide irrelevant actions, disable impossible actions, validate form shape, and show useful auth recovery states. The server must enforce permissions and input validation for every sensitive operation.
Good answer:
401 as unauthenticated and 403 as authenticated but not allowed.Clickjacking tricks a user into interacting with a page framed by another site. The modern answer is to control who can embed the page, usually with the CSP frame-ancestors directive. Older systems may still use X-Frame-Options.
When your app embeds other content, review iframe sandbox permissions, allowed origins, postMessage contracts, and whether sensitive pages can be framed at all.
Common mistake: talking only about CORS. CORS controls browser script access to responses; it does not decide whether another site can frame your page.
Frontend code often runs with access to page content, user interactions, tokens in browser storage, and API responses. A third-party script, tag manager, or compromised dependency can therefore expand the damage from a single bug.
Good answer:
No real secret should be shipped to the browser. Anything in JavaScript bundles, source maps, HTML, network requests, local storage, or devtools-visible config should be treated as public.
Public API keys can be acceptable when the provider expects browser use and enforces restrictions server-side, such as allowed origins, scopes, quotas, and abuse controls. Private API keys, signing secrets, database credentials, and service-role tokens belong on the server.
For OAuth in SPAs, mention PKCE. PKCE improves public-client authorization flows, but it does not turn a browser into a place where client secrets can be hidden.
Service workers can intercept requests, cache responses, and keep behavior active beyond the current page. Review their scope, update strategy, cached sensitive data, logout behavior, and whether an old worker can serve stale authenticated content.
A good answer separates caching bugs from authorization bugs. Clearing UI state on logout is not enough if a service worker can still return sensitive cached responses.
Definitions help, but scenarios show judgment. Practice these as two-minute spoken answers.
| Scenario | What a good answer should reason through |
|---|---|
| User profile bio supports rich text | Plain text versus rich text, allowlist sanitizer, URL protocol validation, safe render path, stored XSS tests, CSP backup |
| Banking transfer uses cookie auth | CSRF token or equivalent server validation, SameSite, Origin/Referer checks, re-auth for high-risk action, no side effects on GET |
Dashboard calls api.example.com from app.example.com | Exact allowed origin, credential mode, preflight behavior, server auth, non-browser client caveat, 401/403 UI |
| Product wants a tag manager on every page | Data exposure, page scoping, CSP impact, consent rules, performance cost, incident response if the script is compromised |
| Admin button is hidden for normal users | UI convenience, server authorization, direct API test, 403 handling, audit logging |
| SPA uses bearer tokens | Storage tradeoff, XSS impact, refresh token flow, rotation, logout, multi-tab behavior |
| Comment preview renders markdown | Sanitized output, unsafe URLs, markdown library defaults, stored payload tests, final DOM inspection |
| App embeds a payment iframe | iframe origin, sandbox permissions, postMessage schema, no wildcard target for sensitive messages |
"Users can write comments with links, bold text, and lists. How would you prevent XSS?"
Start by asking whether the product needs plain text, markdown, or HTML. If plain text is enough, render it as text and avoid HTML. If rich text is required, define an allowlist of tags and attributes, sanitize on a trusted processing path, validate URL protocols, and avoid dangerous DOM sinks in the client.
Then verify the final DOM, not only the stored string. Test stored payloads, reflected payloads, image error handlers, unsafe links, malformed HTML, and post-sanitization mutations. CSP should reduce impact if something slips through, but it is not the primary fix.
Interview-ready answer:
"React escaping handles plain text, but rich text changes the problem. I would keep the allowed formatting small, sanitize with an allowlist, validate links so
javascript:cannot become anhref, render through a controlled component, and test stored comments in the rendered DOM. I would also check which third-party scripts run on the page because they change the impact of an XSS bug."
"The frontend at
https://app.example.comcallshttps://api.example.com/mewith cookies. It works in Postman but fails in the browser."
Postman is not enforcing browser CORS rules. The server must return CORS headers that allow the exact frontend origin. If credentials are included, the frontend request must use the right credential mode, and the server cannot rely on a wildcard origin for a credentialed response.
The API still needs authentication and authorization. CORS decides whether browser JavaScript may read the response; it does not prove that the user is allowed to access /me.
Interview-ready answer:
"I would check the browser console and network panel first. If credentials are involved, I would verify the request credential mode, the exact
Access-Control-Allow-Origin,Access-Control-Allow-Credentials, the preflight response, and the cookie attributes. After that, I would still check the API auth path because CORS is not authorization."
"The UI hides the Delete user button for non-admins. Is that enough?"
No. Hiding the button reduces accidental clicks and keeps the UI cleaner, but it does not enforce permission. A user can call the API directly, replay a request, use another client, or inspect the network request from an admin session.
The server should verify authorization for the delete action. The frontend should handle 403 deliberately, avoid leaking sensitive details, and keep the UI state consistent after a denied request.
Interview-ready answer:
"The frontend should hide the button for UX, but the API must enforce the permission. I would test by calling the endpoint directly as a non-admin and expecting
403. The UI should show a clear not-allowed state and not reveal extra data about the target user."
| Level | What the answer should show |
|---|---|
| Fresher | Can define XSS, CSRF, CORS, cookies, and why frontend validation is not authorization |
| Mid-level | Can identify unsafe rendering paths, token-storage tradeoffs, credentialed CORS risks, and 401/403 UI states |
| Senior | Can design layered defenses, review third-party script risk, coordinate frontend/backend responsibilities, and choose verification steps |
| Staff/lead | Can turn repeated mistakes into platform defaults, CSP rollout plans, dependency policy, review checklists, observability, and incident playbooks |
| Weak answer | Why it falls short | Better direction |
|---|---|---|
| "Use HTTPS" | HTTPS protects transport, not DOM XSS or broken authorization | Name the attack and the matching control |
| "React prevents XSS" | React escapes text by default, but unsafe sinks still exist | Explain the source, sink, and rendering context |
| "Store JWT in localStorage because it is easy" | XSS can read it | Discuss storage tradeoffs, token lifetime, refresh flow, and CSRF if cookies are used |
| "Disable CORS" | CORS is a browser access-control mechanism, not a bug to bypass | Fix the server policy and credential model |
| "Hide the button" | UI hiding is not authorization | Enforce permission on the server and handle 403 in the UI |
| "Add CSP and we are safe" | CSP is defense-in-depth | Keep safe rendering and sanitization as the primary XSS controls |
| "Sanitize input" | Too vague and often wrong for plain text | Say whether you validate input, encode output, or sanitize allowed HTML |
| Topic | Questions worth practicing |
|---|---|
| XSS | What are reflected, stored, and DOM XSS? What are unsafe sinks? How do HTML, attribute, URL, CSS, and JavaScript contexts differ? |
| React and frameworks | Why does React escaping help? How can dangerouslySetInnerHTML become risky? How should untrusted markdown be rendered? |
| Sanitization | When do you encode versus sanitize? Why is an allowlist safer than blocking known bad strings? What can go wrong after sanitization? |
| CSRF | Why do cookies make CSRF possible? How do CSRF tokens, SameSite, Origin checks, and avoiding side effects on GET work together? |
| Cookies | What do HttpOnly, Secure, SameSite, expiration, prefixes, and cookie scope protect against? What do they not protect against? |
| CORS and origins | What is an origin? What triggers a preflight? What changes when credentials are included? Why does CORS not replace authorization? |
| Tokens | Should tokens live in cookies, memory, sessionStorage, or localStorage? How do refresh tokens change the risk? |
| CSP | What does CSP block? What are nonces and hashes? Why can unsafe-inline weaken a policy? How do report-only rollouts help? |
| Trusted Types | What problem does Trusted Types reduce? Which dangerous DOM APIs does it affect? Why is migration work needed? |
| Browser APIs | How do postMessage, iframes, service workers, Web Storage, clipboard APIs, and Web Workers create review points? |
| Frontend permissions | What should the UI hide, what should it disable, and what must the server enforce? How should 401 and 403 states differ? |
| Third-party code | How do analytics, tag managers, embeds, npm packages, and CDN scripts change the damage from a frontend bug? |
| Secrets | Which values can be public in a browser bundle? Which values must stay on the server? Why does PKCE not hide a client secret? |
| Testing | How do you review a PR for XSS risk? What payloads would you test? What belongs in automated tests versus manual review? |
| Incident thinking | If a script was compromised, what data could it read, what actions could it trigger, and what would you rotate or revoke? |
Practice by drawing the boundary first: browser, frontend code, API, cookie jar, third-party script, user-controlled input, storage, or server permission check.
For each answer, name the browser or server boundary and one verification step. For example, an XSS answer should end with a rendered-DOM test; an authorization answer should end with a direct API call using an unprivileged account.

Web performance interview questions test whether you can connect a slow user experience to the browser work causing it. The best answers move from metric to likely cause, then to a measurement plan and a fix.
Do not prepare by memorizing one list of tricks. Practice explaining how loading, rendering, JavaScript, network priority, images, fonts, and user interactions affect the page.
Use current metric names. web.dev Web Vitals lists LCP, INP, and CLS as the current Core Web Vitals, with the 75th percentile target across mobile and desktop. web.dev Learn Performance and MDN critical rendering path are useful references for the browser pipeline behind those numbers.
| Area | What to know | How to answer |
|---|---|---|
| LCP | Largest contentful element, TTFB, render-blocking CSS, image priority | Name the likely LCP element and the first measurement you would check |
| INP | Input delay, event handlers, long tasks, rendering after input | Separate lab TBT from field INP and explain main-thread work |
| CLS | Image dimensions, ads, late fonts, inserted content | Find the moving element and remove unstable layout |
| Rendering | HTML parsing, CSSOM, layout, paint, compositing | Connect a UI symptom to the browser stage that can cause it |
| JavaScript cost | Bundle size, hydration, parsing, execution, memory | Explain what code can be delayed, split, or moved off the critical path |
| Tooling | DevTools, Lighthouse, WebPageTest, CrUX, RUM | Choose the tool based on whether you need lab diagnosis or field impact |
The current Core Web Vitals are LCP for loading, INP for interactivity, and CLS for visual stability. Good thresholds are LCP at 2.5 seconds or less, INP at 200 milliseconds or less, and CLS at 0.1 or less. Assess the 75th percentile of page loads separately for mobile and desktop; a combined number can hide a slow device segment.
Good answer shape:
Common mistake: Listing FID as the current Core Web Vital, forgetting the thresholds, or treating a single Lighthouse run as the whole performance story.
Start by finding the LCP element in field or lab tooling. If it is an image or hero text, check server response time, render-blocking CSS, image size, image priority, font loading, and whether client-side rendering delays the element.
Good answer shape:
Common mistake: Shrinking the JavaScript bundle before checking whether the LCP element is blocked by server latency or an unprioritized image.
INP is based on real interactions. Lighthouse can use lab signals such as Total Blocking Time, but it cannot reproduce every user click, device, extension, background task, and data state. Use Lighthouse for early diagnosis and field data for final confidence.
Good answer shape:
Common mistake: Saying the page is fine because Lighthouse is green while users still report delayed clicks.
It is the work the browser must do before pixels appear: parse HTML, discover resources, build the DOM and CSSOM, run blocking scripts when needed, calculate layout, paint, and composite. The interview value is knowing which resources block which step.
Good answer shape:
Common mistake: Repeating the pipeline but not explaining how a stylesheet, script, or font changes the user experience.
Measure the interaction first. Then reduce synchronous work in the handler, split large updates, avoid unnecessary rerenders, move expensive non-UI work to a worker when appropriate, and keep the visual response close to the input.
Good answer shape:
Common mistake: Adding debounce to every input without understanding whether the delay is network, rendering, or CPU work.
Use code splitting when code is not needed for the first meaningful task: route-level admin screens, heavy charts, editors, maps, or rarely used modals. Do not split tiny modules so aggressively that the page becomes a chain of extra requests.
Good answer shape:
Common mistake: Treating smaller initial JavaScript as automatically better when the app now stalls on many late chunks.
Images affect bytes, decoding, layout stability, and LCP. A good answer covers dimensions, responsive srcset, modern formats, lazy loading below the fold, priority for the LCP image, and avoiding layout shifts.
Good answer shape:
Common mistake: Lazy-loading the hero image that is likely to become the LCP element.
Translate the metric into user pain: slow first content, delayed tap response, or moving layout. Then propose a small fix with a measurable target and a product caveat, such as deferring a carousel or reducing a third-party script.
Good answer shape:
Common mistake: Saying "performance is important" without identifying the user task or business tradeoff.
Use the tool that matches the question. Lighthouse is useful for a repeatable lab snapshot. Chrome DevTools Performance and Network panels help inspect traces, long tasks, waterfalls, layout shifts, and resource priority. WebPageTest is useful for network waterfalls, filmstrips, and device/location testing. CrUX and RUM show whether real users are affected.
Good answer shape:
Common mistake: Saying "I would run Lighthouse" for every problem, including interaction bugs that only happen for real users.
Resource hints change when the browser discovers or prioritizes work. preconnect can warm up a critical third-party origin, preload can fetch a critical resource earlier, and fetchpriority="high" gives the browser a priority hint for the likely LCP image. Classic scripts use defer when order matters and async when it does not; module scripts are deferred by default. Route-level loading can keep code for later interactions off the initial path.
Good answer shape:
Common mistake: Preloading many files because it sounds faster, then making the real critical path noisier.
They reduce network cost, but they do not fix every performance problem. A CDN can reduce latency for static assets and cached HTML. HTTP caching can avoid repeat downloads. Compression reduces transfer size. These help loading metrics, but INP may still be poor if the page ships too much JavaScript or does expensive work after interaction.
Good answer shape:
Common mistake: Saying "put it on a CDN" without checking whether the bottleneck is network, server, rendering, or JavaScript execution.
Profile the interaction or update first. Look for a large rerender, expensive derived data, layout work, too many DOM nodes, heavy third-party components, or hydration cost. Then reduce the render scope, move expensive computation out of the urgent path, virtualize long lists when DOM size is the problem, and use memoization only when the profile shows repeated work.
Good answer shape:
Common mistake: Adding memo, useMemo, or useCallback everywhere before proving rerenders are the bottleneck.
Practice performance answers as diagnosis drills. Start with one symptom, ask what you would measure, then name a fix only after the likely cause is clear.
Answer these aloud as diagnosis exercises. Name the affected metric or user-visible delay, the trace or field signal you would inspect, and how you would verify the change after release.
Start by identifying the LCP element in field data or a trace. Then separate causes: slow TTFB, render-blocking CSS, late image discovery, missing image dimensions, slow image bytes, font blocking, client-side rendering delay, or long main-thread work. A good answer includes the fix order: measure first, improve the biggest bottleneck, ship one change, and compare field data after release.
Bundle size is only one input. INP can be hurt by expensive event handlers, synchronous validation, layout thrashing, rendering too many nodes, heavy third-party code, or state updates that cause a large subtree to rerender. Explain how you would capture a performance trace, find long tasks around the interaction, and move or split work without breaking the interaction.
Reserve dimensions for images, ads, embeds, and recommendation modules before they load. Avoid inserting content above the current viewport, avoid late font swaps that move text, and keep skeleton dimensions close to final dimensions. Mention CLS verification because visual stability problems are often introduced by asynchronous content.
Code splitting helps when it removes non-critical code from the first path. It hurts when critical UI waits for too many chunks, when shared dependencies are duplicated, or when route transitions show blank states because loading boundaries were not designed. A senior answer discusses both network waterfall and user experience.
Prioritize user-visible paths and measured bottlenecks. For example, improve LCP on landing/product pages, INP on search/forms/editors, and CLS on content feeds. Avoid optimizing everything equally. Tie each task to a metric, affected route, expected impact, risk, and verification method.
Interviewers do not expect the same answer from every level. Use this table to calibrate how much depth to add.
| Level | What the answer should show |
|---|---|
| Fresher | Knows the current metrics, can explain loading versus interaction versus layout shift, and can use DevTools or Lighthouse to start debugging |
| Mid-level | Can identify the likely bottleneck, use traces and field data, fix images/scripts/rendering issues, and explain the tradeoff of one optimization |
| Senior | Can prioritize across routes, coordinate backend/frontend ownership, set budgets, instrument RUM, and prevent regressions through release process |
| Staff/lead | Can connect performance to product strategy, architecture, third-party governance, design-system defaults, and observability across teams |
LCP can be split into server response time, resource load delay, resource load duration, and element render delay. That split prevents vague answers. If the image bytes are small but the browser discovers the image late, compressing it again will not fix the main issue. If the element is ready but render is delayed by hydration or CSS, prioritize the render path instead of the asset.
Total Blocking Time is a lab metric that estimates main-thread blocking between FCP and Time to Interactive. INP is a field metric based on real interactions and the next paint after those interactions. TBT can help during debugging, but a good answer says field INP is the user-impact metric.
CSS can block rendering, trigger layout work, create expensive selectors in very large documents, cause layout shifts when late styles arrive, and animate properties that require layout or paint. The practical answer is not "write less CSS"; it is "ship critical CSS carefully, avoid unstable layout, and animate compositor-friendly properties when possible."
Hydration can delay interactivity when the browser must download, parse, execute, and attach event handlers before a UI behaves correctly. A strong answer mentions partial hydration, islands, server components, progressive enhancement, or reducing client-only work, but only after explaining the actual bottleneck.
Tie budgets to routes and user tasks. A useful budget might track LCP image size, JavaScript bytes for the initial route, long tasks during key interactions, CLS from dynamic modules, and third-party script cost. Budgets should have owners and exceptions; otherwise they become ignored dashboards.
Measure its network cost, main-thread cost, and route coverage. Then ask whether it can load after consent, after interaction, on fewer routes, or through a lighter integration. If the business needs the script, isolate it, monitor regressions, and make the owner explicit.
Virtualization helps when the DOM size makes rendering or interaction slow. It adds complexity around keyboard navigation, screen-reader behavior, dynamic heights, scroll restoration, and testing. A good answer says to profile first and keep accessibility behavior intact.
Use the same segment that showed the problem: route, device class, geography, network, and release window. Compare field data after enough traffic has passed, watch error and conversion metrics, and keep a rollback path if the fix changes loading order or user-visible behavior.
Imagine an interviewer says a product detail page feels slow on mobile. A shallow answer jumps straight to "compress images" or "use lazy loading." A better answer asks what users experience and which metric is failing. If the page is slow before the main product image appears, start with LCP. If the page appears but taps lag, start with INP. If content jumps as reviews or recommendations load, start with CLS.
Use this sequence:
The final answer should sound like an investigation plan. For example: "I would first confirm whether LCP or INP is the problem. If LCP is poor and the LCP element is the hero image, I would check discovery, priority, dimensions, and bytes. If those are fine, I would look at TTFB and render-blocking resources. I would verify locally with a trace and later with field data." That answer gives the interviewer a real debugging path.
Avoid listing every performance trick. Interviewers are looking for sequencing and diagnosis. The best answer is usually smaller and more precise than a long checklist.
A good web performance interview answer is not a bag of tricks. It is a measured path from user symptom to browser cause to fix.

Experienced Next.js interviews in 2026 test whether you can choose the right rendering boundary for a product route: static, request-time, client-interactive, server-only, cached, revalidated, or protected before the page renders.
Mid-level and senior candidates are expected to go beyond definitions. Strong answers connect App Router APIs to product constraints: SEO, freshness, secrets, authentication, bundle size, error states, migration risk, and deployment behavior.
If you are preparing for entry-level interviews, start with Next.js Interview Questions for Freshers. This guide assumes you already know the common terms and need to explain tradeoffs, failure modes, and design choices.
The official Next.js App Router docs now show Next.js 16 as the latest line, while many company codebases still run Next.js 14 or 15. Use App Router vocabulary by default, but ask which version and caching setup the team uses before giving version-specific answers.
| Prompt | What it tests | Weak answer |
|---|---|---|
"Build /products/[id]." | Dynamic routes, params, metadata, not-found states | Only describing React Router |
| "Where should this API key live?" | Server-only code and secret handling | Calling the private API from the browser |
| "Why is this page stale?" | Caching, revalidation, dynamic rendering | Saying only "clear cache" |
| "Why did hydration fail?" | Server/client markup mismatch | Blaming CSS or React without naming the mismatch |
| "Add a cart button to a product page." | Server and Client Component boundaries | Marking the whole route as client-rendered |
"Protect /dashboard." | Auth checks before protected UI renders | Redirecting only in useEffect |
Next.js is a React framework for building web applications. It adds file-system routing, server rendering, static generation, Server Components, data fetching conventions, metadata, route handlers, image and font optimization, and deployment patterns around React.
React gives you the component model. Next.js gives you the application structure.
The App Router is the modern routing system based on the app/ directory. It uses route segments, page.tsx, layout.tsx, Server Components, Client Components, loading UI, error boundaries, Route Handlers, metadata APIs, and caching controls.
For new projects, answer App Router questions with app/ concepts first. Mention the Pages Router only when comparing older APIs such as getStaticProps or getServerSideProps.
In the App Router, folders define route segments. A segment becomes publicly routable when it has a page.tsx file.
app/page.tsxproducts/page.tsx[id]/page.tsx
This creates /, /products, and /products/:id.
page.tsx and layout.tsx?page.tsx renders the UI for a route. layout.tsx wraps a route segment and its children. Layouts are useful for shared navigation, sidebars, shells, and providers that should persist across navigation.
Use a page for route-specific content. Use a layout for shared structure.
Dynamic routes capture variable URL segments with folder names such as [id], [slug], [...slug], or [[...slug]].
export default async function ProductPage({params,}: {params: Promise<{ id: string }>;}) {const { id } = await params;return <h1>Product {id}</h1>;}
In current App Router examples, params may be treated asynchronously. Follow the project's Next.js version and conventions.
For an interview, say the important part out loud: [id] is the dynamic segment, params.id is the value from the URL, and the page should still handle a missing or invalid product with notFound().
Server Components render on the server and do not ship their component code to the browser. They are useful for reading server-only data, calling databases, using secrets, rendering static content, and reducing client JavaScript.
They cannot use browser-only APIs, event handlers, or client hooks such as useState.
Client Components run in the browser. Add "use client" at the top of the file to create a client boundary.
Use Client Components for click handlers, local state, effects, browser APIs, focus behavior, and interactive widgets.
"use client"?Use "use client" only for the component subtree that needs browser interactivity. A product page can be a Server Component while an AddToCartButton inside it is a Client Component.
The common mistake is marking the entire route as client-rendered because one button needs onClick.
Yes. A Server Component can import and render a Client Component, passing serializable props. This is the normal pattern for mixing server-rendered content with small interactive islands.
A Client Component should not directly import a Server Component. Instead, pass server-rendered children from a server parent when needed.
Hydration is the process where React attaches client-side behavior to server-rendered HTML. Hydration warnings happen when the initial client render does not match the HTML produced on the server.
Common causes include rendering Date.now(), Math.random(), locale-dependent text, or localStorage-dependent values during the first render.
Use notFound() when route data does not exist, and define a not-found.tsx file when the route needs custom not-found UI.
Do not silently render an empty page for a missing product. A missing resource is a route-level state.
Use redirect() when server-side route logic determines the user should go elsewhere, such as after an auth check or missing required setup.
Client-side navigation is still useful for user-initiated interactions, but protected content should not flash before a redirect.
Use static metadata for fixed route metadata and generateMetadata() when metadata depends on route params or fetched data.
For a product detail page, use the product title, description, canonical URL, and open graph image from server-side data.
loading.tsx?loading.tsx defines route-level loading UI. It works with Suspense boundaries so the user can see an immediate loading state while route content is prepared.
Good answers mention the user experience: a slow product page needs a stable loading layout, not a blank screen.
error.tsx?error.tsx defines an error boundary for a route segment. It must be a Client Component because error boundaries need client behavior.
Use it for recoverable route errors. Do not treat it as a replacement for validating data and handling expected empty states.
Use static generation when the route can be generated ahead of time and stale content is acceptable until the next build or revalidation. Use request-time rendering when the response depends on user-specific data, cookies, headers, permissions, or strict freshness.
Most product pages are mixed: marketing copy can be cached, while inventory or price may need revalidation or dynamic fetching.
In newer Next.js projects, you may also hear about Cache Components. The interview answer is still the same at the product level: decide which parts may be reused, which parts are request-specific, and where Suspense should show a loading state while uncached data resolves.
generateStaticParams()?generateStaticParams() returns params for dynamic routes that should be generated at build time.
Use it for known blog slugs, documentation pages, marketing pages, or product pages where the catalog is known and build-time generation is reasonable.
fetch()?Next.js extends server-side fetch() with persistent caching and revalidation controls. Defaults have changed across recent versions and can also depend on project configuration, so avoid giving a memorized default as if it were universal. Interviewers usually care more about whether you make freshness explicit for important data.
For example, product copy can be cached longer than stock status. A dashboard for the signed-in user should not share cached private data across users.
Useful answer pattern:
Revalidation updates cached data after time passes or after an event. Time-based revalidation is useful for data that can be a little stale. On-demand revalidation is useful after a CMS publish, catalog update, or admin action.
Name the freshness requirement before choosing a revalidation strategy.
Search routes often depend on query params, user input, ranking, and freshness. Avoid treating every possible search query as a prebuilt static page.
Depending on SEO and interactivity needs, render results on the server, fetch them on the client, or combine a server-rendered shell with client-side refinements.
Route Handlers let you define server endpoints inside the App Router, commonly with route.ts. Use them for API endpoints, webhooks, server-side data access, and integrations that should not expose secrets to the browser.
Secrets should stay on the server: Server Components, Server Functions, Route Handlers, or other server-only code. Do not expose private API keys through Client Components or public environment variables.
Server Functions run on the server and can be called from application code for mutations or server-side work. In interviews, explain why the server boundary matters: validation, authorization, secret access, and trusted writes belong on the server.
Validate on the client for fast feedback and on the server for trust. Client validation improves UX. Server validation enforces the rule.
A good form answer includes pending state, duplicate-submit prevention, error display, and accessible field messages.
Read auth state from trusted server-side signals such as cookies or headers. Redirect unauthenticated users before rendering protected UI when the server has enough information.
For broad route gates, Next.js docs now use the term Proxy for pre-route logic. Some teams may still say Middleware because older versions and codebases used that term.
Do not put all authorization logic only in Proxy. It is useful for early routing decisions, but data access and mutations still need server-side authorization at the point where protected data is read or changed.
Keep non-interactive UI as Server Components, put "use client" at small boundaries, avoid importing large browser-only libraries into shared parents, and measure bundle output before optimizing blindly.
Next.js provides an Image component and image optimization features. In interviews, explain the product reason: reserve layout space, serve appropriately sized images, avoid unnecessary downloads, and protect performance metrics such as LCP.
Next.js font optimization helps load fonts with less layout shift and clearer ownership. The key interview point is that font loading affects perceived performance, layout stability, and branding consistency.
Split the problem:
Then measure with framework build output, browser DevTools, server logs, and Web Vitals.
Development mode optimizes feedback for engineers. Production builds optimize output for users. Caching, bundling, minification, image behavior, and deployment environment can differ.
If a bug appears only in production, check environment variables, build-time assumptions, server/runtime differences, and caching.
Use a Server Component page for product data and SEO. Generate metadata from product data. Return notFound() for missing products. Keep interactive parts such as cart controls, variant selectors, and wishlist buttons in small Client Components. Make freshness explicit for price and inventory.
Check auth before rendering protected UI. Fetch user-specific data on the server with request-aware credentials. Avoid sharing cached private responses. Split slow widgets with Suspense when possible. Keep URL state for filters that users expect to share or revisit.
Do not rewrite everything at once. Migrate route by route, learn the new data and rendering model, replace getStaticProps and getServerSideProps with App Router patterns, move shared shells into layouts, and identify Client Component boundaries.
The biggest migration risk is carrying old mental models into Server Components and caching.
Good migration answers also mention compatibility work: routes may coexist during migration, shared components may need "use client" boundaries, API routes may move to Route Handlers only when there is a reason, and tests should cover redirects, metadata, and not-found behavior before and after the move.
Make the first client render match the server HTML. Avoid browser-only reads during render. Move browser-only logic into effects, use cookies when the server needs the value, or render a deliberate client boundary for values that cannot be known on the server.
Use server fetching when data improves SEO, uses secrets, depends on trusted auth, or should avoid extra client waterfalls. Use client fetching for highly interactive data, browser-only context, live updates, or user actions after initial render.
The answer should include the UI states either way.
Do not let one optional widget break an entire page. Use route error boundaries for route-level failures, local error UI for widget-level failures, and server-side validation for expected missing data.
Name which failures are fatal and which can degrade.
Separate route concerns: data loading, metadata, UI composition, interactive client widgets, mutation boundaries, and error states. Avoid making page.tsx a long file that owns every detail.
Test pure utilities with unit tests, components with user-focused component tests, and critical flows with E2E tests. For framework-specific behavior such as redirects, route handlers, and server boundaries, test at the route or integration level where possible.
Check whether secrets stay on the server, client boundaries are small, route states are handled, metadata is correct, caching is explicit where freshness matters, and loading/error/not-found states match the product requirement.
Use this structure:
That pattern turns framework knowledge into product judgment, which is what stronger Next.js interviews usually measure.

Vue.js interviews in 2026 test whether you understand Vue 3 reactivity, component communication, Single-File Components, Composition API, routing, state, and performance tradeoffs.
The strongest answers do not sound like API lists. They explain how data changes, which component owns it, how the template updates, and what happens when the app grows.
The official Vue introduction documents Vue 3 as the current guide, with Single-File Components for build-tool projects and Composition API plus SFCs as the recommended path for full applications.
| Prompt | What it tests | Common mistake |
|---|---|---|
| "Why did this template update?" | Vue reactivity | Saying "Vue watches everything" without explaining refs/proxies |
| "Should this be a prop, emit, or store value?" | State ownership | Putting all shared data in a global store |
| "Build a reusable modal." | Slots, emits, accessibility, lifecycle | Hard-coding content and forgetting focus behavior |
| "Fetch data for this route." | Lifecycle, async state, routing | Ignoring loading, empty, and error states |
| "This list is slow." | Keys, computed data, virtualization | Re-rendering a huge list and blaming Vue |
Vue.js is a JavaScript framework for building user interfaces. It uses components, declarative templates, reactive state, directives, and an ecosystem for routing, state management, tooling, and server rendering.
Vue can be used progressively on part of a page or as the framework for a full application.
A Single-File Component, usually a .vue file, keeps a component's template, script, and styles in one file.
<template><button @click="count++">Clicked {{ count }} times</button></template><script setup lang="ts">import { ref } from 'vue';const count = ref(0);</script>
SFCs are common in build-tool-enabled Vue projects because they keep the component's UI, logic, and local styles close together.
The Composition API is a Vue API style where component logic is written with functions such as ref, reactive, computed, watch, and lifecycle hooks inside setup or <script setup>.
It is especially useful when a component has several related pieces of logic or when logic should be extracted into composables.
The Options API organizes a component into options such as data, methods, computed, watch, and lifecycle hooks.
It is still valid Vue. In interviews, avoid presenting Composition API as "new good" and Options API as "old bad." Explain the tradeoff: Options API is approachable for simpler components, while Composition API scales better for shared logic and complex features.
ref()?ref() creates a reactive value. In script, read and write the value through .value. In templates, refs are automatically unwrapped.
const count = ref(0);count.value += 1;
Use ref for primitives and often for values that may be replaced.
reactive()?reactive() creates a reactive proxy for an object.
const form = reactive({email: '',password: '',});
Use it for object state where you want to mutate properties. Be careful when destructuring because destructuring can lose reactivity unless you use helpers designed for that case.
For example, destructuring const { email } = form gives you the current value, not a reactive binding. Use toRefs() when separate reactive bindings are needed:
import { reactive, toRefs } from 'vue';const form = reactive({email: '',password: '',});const { email, password } = toRefs(form);
That is a common source of "why did my template stop updating?" interview questions.
computed and watch?Use computed for derived values that can be calculated from reactive state.
Use watch for side effects when a reactive value changes: calling an API, syncing with storage, logging analytics, or bridging to non-Vue code.
If you can calculate it during render, use computed instead of watch.
Directives are special template attributes that apply reactive behavior. Common examples include:
v-if for conditional renderingv-show for toggling visibility with CSSv-for for listsv-bind or : for binding attributesv-on or @ for eventsv-model for two-way form bindingsv-if and v-show?v-if conditionally mounts or unmounts DOM. Use it when the condition changes rarely or when the component should not exist until needed.
v-show keeps the element in the DOM and toggles display. Use it for frequent visibility changes where mount cost matters less than toggle speed.
v-for?Keys help Vue track item identity across list updates. Use stable IDs when rendering lists that can change order, insert, remove, or filter.
Index keys can preserve state on the wrong row when the list changes.
Props pass data from parent to child. A child should treat props as read-only input.
<script setup lang="ts">defineProps<{title: string;completed: boolean;}>();</script>
If the child needs to request a change, emit an event instead of mutating the prop.
Emits let a child component notify its parent that something happened.
<script setup lang="ts">const emit = defineEmits<{save: [id: string];}>();function saveTodo(id: string) {emit('save', id);}</script>
The parent owns the state change. The child reports the user action.
v-model on a component?v-model creates a two-way binding convention between a parent and child component. In Vue 3, component v-model is based on a prop and an update event.
Use it for form-like components such as inputs, selects, toggles, and date pickers. Avoid hiding complex business updates behind v-model when explicit events would be clearer.
In current Vue, defineModel() is the concise way to declare a component model in <script setup>. In older or more explicit code, the same idea appears as a modelValue prop and an update:modelValue event. Knowing both helps in interviews because many production codebases mix versions and styles.
Slots let a parent pass template content into a child component.
Use slots for layout components, cards, modals, tables, and reusable shells where the child owns structure but the parent owns content.
Scoped slots let the child expose data to the slot content.
They are useful for reusable list, table, or form components where the child manages behavior and the parent controls rendering.
provide and inject pass values through a component tree without prop drilling.
Use them for shared context such as theme, form context, table context, or dependency-style values. Do not use them to hide ordinary parent-child data flow.
Vue tracks reactive reads during rendering or effects, then updates the affected parts when reactive values change. In Vue 3, object reactivity is built on JavaScript proxies, while refs wrap individual values.
The interview goal is to explain dependency tracking and updates without claiming Vue "rerenders everything."
A composable is a function that uses Vue Composition API features to package reusable stateful logic.
import { onMounted, onUnmounted, ref } from 'vue';export function useWindowWidth() {const width = ref(0);function updateWidth() {width.value = window.innerWidth;}onMounted(() => {updateWidth();window.addEventListener('resize', updateWidth);});onUnmounted(() => window.removeEventListener('resize', updateWidth));return { width };}
Good composables clean up side effects and expose a small API.
Common Composition API hooks include:
onMounted for browser-only setup after mountonUpdated for reacting after DOM updates when neededonUnmounted for cleanuponErrorCaptured for handling descendant errorsDo not fetch data in a lifecycle hook by reflex. In router-based apps or SSR, data loading may belong at the route or framework layer.
watch and watchEffect?watch observes explicit sources and runs when those sources change. It is better when you want control over what triggers the effect.
watchEffect runs immediately and tracks reactive values used inside it. It is convenient, but less explicit.
Use watch when correctness depends on a specific source.
Vue Router maps URLs to components and supports route params, query params, nested routes, navigation guards, lazy-loaded route components, and active links.
A good routing answer includes user states: loading, not found, unauthorized, and error.
For a simple client-rendered component, use reactive request state and fetch data when the route or input changes. In a framework or SSR setup, prefer the framework's data-loading pattern.
Always model:
Pinia is the commonly used state management library in the Vue ecosystem. Use a store for state shared across unrelated components or routes, such as auth user, cart, preferences, or app-wide entities.
Do not move every local form value into a store. Local state is easier to reason about when only one component owns it.
A good Pinia answer also separates server cache from client state. If the data mainly comes from the server and needs refetching, invalidation, pagination, or background refresh, a data-fetching layer or framework loader may be a better fit than manually copying everything into a store.
Put shareable, bookmarkable state in the URL: search query, filters, sort order, page number, and selected tab when the user expects back-button behavior.
Keep ephemeral UI state local: open menus, draft input, hover state, and one-off loading flags.
Use v-model for field values, validation for user feedback, and explicit submit handling for server work.
A good form answer includes labels, accessible errors, disabled pending state, server-side validation, and duplicate-submit protection.
Use props for open state, emits for close/confirm events, slots for content, and lifecycle or composables for focus trapping, Escape handling, and scroll locking. Keep accessibility requirements explicit: role, label, focus return, and keyboard behavior.
First identify the bottleneck. Use stable keys, avoid expensive work directly in templates, move derived data to computed values, paginate or virtualize long lists, lazy-load heavy rows, and measure before changing architecture.
Also check whether the list reactivity is too deep for the job. For large immutable datasets, shallowRef() can be useful because Vue tracks replacement of the array rather than every nested property. That is a senior-level answer only when you can explain the tradeoff: nested mutation will not trigger updates the same way.
Group by feature when features are large enough: route, components, composables, store, API client, tests, and types. Keep truly shared UI in a shared component area. Avoid a giant global components folder full of one-off pieces.
Use props and emits for direct parent-child communication. Use provide/inject for context shared by a component subtree. Use Pinia when unrelated parts of the app need the same state or actions.
The decision is about ownership and reach.
Test user-visible behavior: rendered text, form interactions, emitted events, loading states, error states, and accessibility-critical behavior. Avoid tests that only assert implementation details such as private method calls.
Common mistakes include unstable keys, deep watchers on large objects, expensive computed work over huge arrays, unnecessary global state updates, rendering too many rows at once, and importing large dependencies into frequently used components.
Clean up event listeners, timers, subscriptions, observers, and third-party library instances in onUnmounted. Composables that create side effects should own their cleanup.
Know how to type props, emits, refs, computed values, composables, API responses, and store state. With <script setup lang="ts">, keep component contracts close to the component.
Do not type everything as any to make the template pass. That removes the main value of TypeScript.
Check state ownership, prop mutation, event names, stable keys, computed versus watcher usage, cleanup for side effects, accessible form and modal behavior, route states, and whether shared code is genuinely reusable.
Use this structure:
That keeps your answer practical whether the prompt is a small component, a route, or a senior architecture question.
Build these small features:
| Feature | Skills tested |
|---|---|
| Todo list | ref, computed, v-for, keys, emits |
| Search page | async state, route query, loading and errors |
| Modal | slots, emits, lifecycle, keyboard behavior |
| Data table | props, scoped slots, derived rows, pagination |
| Cart store | Pinia, actions, derived totals, persistence |
| Form wizard | v-model, validation, step state, accessibility |
Pair Vue practice with general frontend practice: JavaScript data work, CSS layout, browser APIs, accessibility, and UI problem solving. Vue gives you a productive component model, but interviews still reward careful frontend judgment.

Frontend developer jobs in Pune are a good target in 2026 if you can handle practical UI work: React or Angular, JavaScript, CSS, APIs, performance basics, and readable code.
Pune has a mixed frontend market. You will see product companies, IT services, GCC teams, agencies, industrial tech, banking and finance products, analytics products, trainee roles, and senior frontend openings. Some roles are modern React product work. Some are Angular enterprise work. Some are web developer roles where HTML, CSS, Bootstrap, jQuery, CMS, and quick delivery matter.
That means your preparation should not copy a Bangalore or remote-only plan. Pune rewards candidates who can identify the kind of frontend work behind the title and show matching proof. Start by asking: is this product UI, enterprise delivery, agency/CMS work, or junior implementation work?
For stack choices, use data as a guardrail. In the 2025 Stack Overflow Developer Survey, professional developers reported broad use of JavaScript, HTML/CSS, TypeScript, React, Next.js, Angular, and jQuery. That matches Pune's mix: modern frontend roles exist, but some web developer jobs still value practical CSS, DOM, CMS, and legacy-code comfort.
Use the job description to classify the role.
| Role pattern | Likely work | What to show |
|---|---|---|
| Front-End Developer, 1-3 years | websites, client-side pages, Bootstrap, basic React, responsive UI | polished layouts, JS interactions, deployed projects |
| React Developer | product screens, API data, components, app state | React project with forms, tables, routing, and error states |
| Angular Developer | enterprise apps, dashboards, forms, services, modules | Angular forms, typed services, reusable components |
| Junior React/JavaScript Developer | small features, bug fixes, REST APIs, some backend adjacency | clean JavaScript, React basics, API-backed project |
| UI / Front-End Developer | layout, CSS, browser behavior, design handoff | responsive CSS, accessibility basics, visual care |
| Senior Frontend Developer | architecture, performance, mentoring, cross-team work | case studies, tradeoffs, performance and review examples |
| Trainee Frontend Developer | HTML, CSS, Bootstrap, JS, jQuery, learning on the job | finished beginner projects and GitHub discipline |
The mistake is applying to all of these as if they are the same. A trainee role needs evidence of learning speed and clean basics. A senior React role needs ownership, state decisions, and product judgment.
| Company type | Frontend work you may see | Best preparation |
|---|---|---|
| IT services | client apps, feature delivery, framework variety, maintenance | one framework plus adaptable JavaScript and CSS |
| Product companies | dashboards, workflows, customer features, API integration | product-style projects with edge states |
| GCCs | larger codebases, code review, testing, maintainability | TypeScript, component boundaries, readable PRs |
| Agencies | websites, campaign pages, responsive UI, CMS work | visual polish, CSS, browser compatibility |
| Industrial and construction tech | data tables, reports, project tools, internal systems | table-heavy UI, filters, charts, permissions |
| Fintech and operations teams | forms, KYC-like flows, approvals, audit screens | validation, disabled states, error recovery |
Choose one primary lane and one backup lane. For example:
Or:
This keeps your resume and portfolio consistent. It also prevents the common Pune job-search mistake: applying to a senior Angular enterprise role, a React product role, and a trainee UI role with the same project order and the same resume bullets.
Pune's company mix is different from Bangalore and Hyderabad. It has strong services, enterprise product, banking/finance, industrial tech, SaaS, and GCC-style work. Treat the names below as research targets, not a universal ranking.
| Company group | Examples to research | Frontend angle to look for |
|---|---|---|
| Pune-headquartered or Pune-strong tech companies | Persistent Systems, PubMatic, Druva, BMC Software, Zensar, Cybage | product engineering, SaaS dashboards, enterprise UI, platform tools, frontend performance |
| Banking, finance, and enterprise GCCs | Mastercard, Barclays, UBS, Citi, Deutsche Bank, Credit Suisse/UBS teams | forms, approvals, data-heavy screens, security, reliability, internal tools |
| Industrial, engineering, and B2B tech | Siemens, PTC, Dassault Systemes, vConstruct, NICE | complex workflows, data visualization, internal platforms, domain-heavy UI |
| Services and consulting companies | Infosys, TCS, Cognizant, Capgemini, Accenture, Tech Mahindra, Wipro | client delivery, Angular/React projects, migrations, support, multi-stack exposure |
| Startups and local product teams | SaaS, edtech, logistics, developer-tools, and agency-style teams | faster ownership, practical UI delivery, broader responsibilities |
If you want frontend depth, read the job description carefully. A strong Pune role can come from a product company, a GCC, or a services team, but the work should include UI ownership: forms, tables, APIs, performance, accessibility, or reusable components. If the listing only names tools, ask what screen or workflow the team owns.
The safest stack is:
If you are choosing between React and Angular, do not treat it as an identity decision. Search current Pune openings, count which framework appears in your target lane, and build one serious project in that framework. Keep JavaScript and CSS separate from the framework; those are what keep you employable when the codebase is older than the job post.
If you are still learning, follow How to Become a Frontend Developer in 2026 before applying heavily.
Build projects that match the work Pune companies actually hire for.
This fits product, analytics, industrial, services, and GCC roles.
Include:
Add a README note explaining the table state, why filters live where they live, and how you would connect the screen to a backend.
Good options:
Include:
This project works well because it is closer to internal-tool frontend work than a clone of a streaming homepage.
Do not ignore CSS. Pune has many roles where layout quality matters.
Include:
This project helps for web developer, agency, and UI roles.
Write bullets that describe behavior.
| Level | Weak bullet | Better bullet |
|---|---|---|
| Fresher | Made React projects | Built a React job tracker with filters, local persistence, empty states, and responsive layout |
| 1-2 years | Worked on UI pages | Implemented reusable form fields with validation messages and API error handling |
| 3-5 years | Developed frontend features | Owned an Angular approval workflow with typed services, role-based actions, and release fixes |
| Senior | Managed frontend work | Led a React performance pass on a data-heavy page by reducing unnecessary renders and table work |
If you do not have work experience, use project bullets. If you do have work experience, prioritize shipped work over personal projects.
Expect a practical interview bar. You may get a mix of JavaScript, CSS, framework questions, project discussion, and UI coding.
Prepare:
map, filter, reduce, sort, and mutation pitfallsasync/awaitPrepare:
For React:
For Angular:
Practice JavaScript interview questions, React interview questions, Contact Form, Data Table, Modal Dialog, and Tabs.
| Days | Work |
|---|---|
| 1-5 | Pick primary lane: React product, Angular enterprise, UI/web, or fresher/trainee |
| 6-12 | Fix JavaScript and CSS gaps with small exercises |
| 13-22 | Build or improve one product-style project |
| 23-28 | Add TypeScript or Angular/React depth based on your target lane |
| 29-32 | Clean GitHub, READMEs, live links, and screenshots |
| 33-36 | Rewrite resume bullets for Pune roles |
| 37-45 | Apply daily, practice interviews, and record questions asked |
Use interview feedback as data. If three interviews expose weak CSS, stop adding React libraries and fix CSS. If every role asks for Angular and your target is enterprise Pune, adjust. If you get no callbacks, check whether your live demos work on mobile and whether your resume says what you actually built.
Freshers should not try to look senior. Look reliable.
Your first-role proof should include:
Apply to internships, trainee roles, junior UI roles, and small companies where you can learn. Read Frontend Developer Jobs for Freshers: How to Get Your First Role in 2026 for the full first-role process.
If you have experience, build your pitch around ownership:
Use Frontend Developer Career Path: From Junior to Senior in 2026 to map your examples to the next role.
Ask:
The answers help you decide whether the role builds the frontend career you want.
Frontend developer jobs in Pune reward practical preparation. Match the role type, build proof for that lane, prepare JavaScript and CSS seriously, and show that you can deliver UI that works beyond the first happy path.

Remote frontend developer jobs are available in 2026, but they are harder to win than local roles. You need frontend skill, written proof, async work habits, timezone fit, and a portfolio that earns trust quickly.
Remote hiring changes the signal. In an office interview, a team may rely on energy, conversation, and local availability. In a remote hiring process, the team looks for proof that you can work without constant supervision: clear writing, small deliverables, good questions, and code that can be reviewed asynchronously.
That matters for frontend because the work sits between product, design, backend, QA, analytics, and users. If your communication is vague, remote frontend work becomes slow quickly.
The opportunity is real, but not evenly distributed. In the 2025 Stack Overflow Developer Survey work section, respondents in India reported a mix of remote, hybrid, flexible, and in-person work rather than a remote-only market. Treat remote as a competitive role type, not as a shortcut around local hiring.
Remote frontend roles often ask for the same technical stack as local roles, but they add trust signals.
| Area | What companies look for | How to show it |
|---|---|---|
| Framework skill | React, Angular, Vue, Svelte, or Next.js experience | project or case study with complete flow |
| JavaScript and TypeScript | reliable app behavior and safer code | typed API data, state models, fewer assumptions |
| Product UI | forms, dashboards, user flows, API states | deployed demos with loading, empty, error, retry |
| Review habits | code that can be reviewed without a meeting | readable commits, README, pull-request notes |
| Async work | can explain decisions in writing | case studies, technical notes, issue-style project docs |
| Timezone overlap | can collaborate at predictable times | mention preferred overlap and location clearly |
| Ownership | can move work forward when requirements are incomplete | examples of questions, tradeoffs, and follow-through |
Remote does not mean easier. It often means the company has more applicants and less patience for unclear proof. A remote application has to answer doubts before the first call: Can this person write clearly? Can they ship without hand-holding? Can we review their code without a meeting?
Use more than one source. Remote roles appear and fill quickly.
Search terms:
remote frontend developerremote frontend engineerremote React developerremote Next.js developerremote Angular developerremote UI developerfrontend developer work from homefrontend engineer async remoteUse these channels:
| Channel | How to use it |
|---|---|
| Remote job boards | Apply quickly, but only when the stack and timezone fit |
| Company career pages | Search companies that already hire distributed teams |
| Filter by remote, then verify the company page | |
| Startup platforms | Look for early teams needing product frontend work |
| Communities | React, JavaScript, design-system, and indie-hacker communities |
| Previous network | Ask former coworkers about distributed teams |
Do not spend all day clicking easy-apply buttons. Remote hiring rewards targeted applications. Save the job post, because remote listings are edited or closed quickly and you may need the original requirements while preparing.
Some remote roles are excellent. Some are unclear, low-trust, or not truly remote.
| Filter | Good signal | Red flag |
|---|---|---|
| Timezone | clear overlap, such as IST plus Europe or IST plus US morning | "global remote" but no meeting expectations |
| Employment type | full-time, contract, freelance, or internship is explicit | vague role with unclear legal setup |
| Pay | range, band, or early compensation conversation | pay hidden until late rounds |
| Process | written docs, code review, async tools | constant online monitoring |
| Role scope | frontend ownership is described | only a stack list with no work context |
| Assignment | time-boxed and relevant | unpaid product work disguised as a test |
| Communication | official email, normal contract process | personal payment requests or strange onboarding |
If the role is remote but expects you to be online all day with no autonomy, evaluate whether it actually gives you the remote work you want.
Also verify the basics before sharing documents: company domain, recruiter identity, written offer process, payment schedule for contracts, equipment policy, and whether the role is remote from your country or only remote inside one country.
A remote portfolio should explain your work even when you are asleep in another timezone.
Include:
Your case studies should answer:
Add one remote-specific detail to at least one case study: the written issue, handoff note, README, pull-request description, or decision log you would use if teammates reviewed the work later. Remote teams hire for evidence that work can move while people are offline.
For experienced developers, read Frontend Developer Portfolio: What to Build and What to Show in 2026. For freshers, use How to Build a Frontend Developer Portfolio With No Experience (2026).
Remote teams judge writing early.
Your proof can include:
Use this project note structure:
Context:What the feature does and who uses it.Constraints:Time, API shape, device support, or design limits.Decisions:State ownership, component boundaries, data fetching, accessibility, or performance choices.Quality:Tests, manual checks, keyboard checks, known limitations.Next:What you would improve with more time.
This is not extra decoration. It shows how you would work in a distributed team. A short, clear note beats a long case study that never names the constraints.
Remote applications need to be more targeted because competition is wider.
Use this process:
Track timezone and country restrictions separately. Many listings say "remote" but require a legal entity, payroll setup, or working-hours overlap that may exclude you.
Application note:
Hi [Name],I am applying for the remote frontend role. The role mentions React, TypeScript, and dashboard work, which matches this project: [link].I built filtered tables, URL-based state, loading/error handling, and a responsive layout. I also wrote a short case study with the main frontend decisions: [link].I am based in [location] and can overlap with [timezone/window].
Customize the middle paragraph. If the job mentions design systems, point to component work. If it mentions SaaS dashboards, point to table and API work. If it mentions e-commerce, point to cart, checkout, and performance.
Prepare your environment and your thinking.
Practice:
Do:
Do not:
For take-home assignments, include a short README with scope, run commands, assumptions, tradeoffs, and what you would improve with more time. That README is part of the interview, not paperwork.
Practice front end system design questions, React interview questions, Data Table, Autocomplete, and File Explorer.
Freshers can apply to remote roles, but should be careful. Many remote fresher roles are internships, freelance tasks, or small-company work with limited mentoring.
Before accepting, ask:
If you have no experience, a good local or hybrid internship with real mentorship can be better than a poorly managed remote role. Remote fresher work is safest when there is a named reviewer, clear weekly feedback, and a written task process.
Experienced developers should prepare ownership stories.
Show:
Remote senior roles often care less about whether you can write a component and more about whether work moves forward when nobody is sitting beside you.
Good senior proof includes artifacts: a design note, migration plan, incident write-up, performance measurement, accessibility checklist, or pull-request description that shows how you reduce ambiguity for others.
Avoid:
Remote frontend jobs go to candidates who lower hiring risk.
Remote frontend developer jobs in 2026 require visible trust. Build proof that can be reviewed asynchronously, write clearly, filter roles carefully, and prepare to show how you move frontend work forward without constant supervision.

Frontend developer jobs in Bangalore are competitive because the city attracts many applicants, but the city also gives frontend engineers more role variety than most Indian markets: product companies, startups, GCCs, SaaS teams, fintech, agencies, and design-heavy web teams.
That mix is useful only if your preparation is targeted. A generic "HTML, CSS, JavaScript, React" resume will disappear quickly. A portfolio that proves product UI, API integration, state handling, performance awareness, and clear frontend decisions has a much better chance.
Bangalore rewards candidates who can move beyond course projects and talk like someone who understands product frontend work: designs change, APIs fail, requirements are incomplete, users make mistakes, and code has to survive review.
One current signal supports that stack choice: in the 2025 Stack Overflow Developer Survey, professional developers reported heavy use of JavaScript, HTML/CSS, TypeScript, React, Next.js, and Angular. Use that as a broad market signal, not as proof that every Bangalore job uses the same stack.
Bangalore has more role variety than most Indian cities. You will see:
This means there is no single Bangalore frontend path. A fresher applying to internships, a React developer with two years of experience, and a senior engineer targeting GCCs need different proof. Before you apply, classify the role: product frontend, UI implementation, enterprise app, design system, CMS/web, or frontend platform.
Do not treat this as a fixed ranking. "Top company" depends on whether you want product engineering, startup pace, enterprise scale, design systems, compensation, mentorship, or frontend depth. Use this list as a starting point for research, then check current openings and team fit.
| Company group | Examples to research | Frontend angle to look for |
|---|---|---|
| Global product and platform companies | Google, Microsoft, Amazon, Adobe, Intuit, Salesforce, Atlassian, Walmart Global Tech | product UI, platform tools, internal systems, design systems, performance, accessibility |
| Indian consumer and fintech product companies | Flipkart, PhonePe, Razorpay, Swiggy, Meesho, CRED, Groww, Zepto | high-traffic UI, checkout flows, payments, experimentation, mobile web, customer-facing product work |
| SaaS and B2B product teams | Freshworks, Zoho, BrowserStack, Chargebee, Postman, Whatfix | dashboards, admin tools, onboarding flows, developer tools, customer workflows |
| Services and consulting companies | Accenture, Infosys, Wipro, TCS, Cognizant, Capgemini, Thoughtworks | client projects, migrations, enterprise apps, Angular/React delivery, broader stack exposure |
| Design-led and agency-style teams | product studios, design agencies, brand-tech teams, marketing-tech teams | CSS, visual polish, responsive implementation, CMS, campaign pages |
Shortlist companies by role quality, not brand alone. A smaller product team where you own a checkout flow can be better for frontend growth than a famous company where you only maintain a narrow internal page.
When researching a company, look for three things before sending the resume: recent frontend openings, product screenshots or docs that reveal the UI complexity, and engineering posts or job descriptions that mention review, testing, accessibility, performance, or design systems. If all you can find is a stack list, treat the role as unverified until a recruiter or engineer explains the work.
Read the job description like an engineer, not like a keyword scanner.
| Listing signal | What the role likely involves | What to show |
|---|---|---|
| "front-facing experiences" or "user-facing features" | Product UI that customers use daily | Polished product screens with edge states |
| "reusable components and libraries" | Component architecture or design system work | Component APIs, variants, docs, and examples |
| "backend developers and product teams" | API integration and cross-team work | Loading, error, auth, retry, and data-shape handling |
| "AI-powered developer tools" | AI-assisted workflows or developer productivity UI | Good review habits and ability to verify generated code |
| "high-performance web applications" | Rendering, bundle, image, or interaction cost matters | Measured improvements and performance notes |
| "onsite contract" | Delivery speed and availability may matter more than brand | Clear scope, rate, duration, and ownership expectations |
| "webmaster" or "WordPress" | CMS, marketing sites, hosting, SEO, and plugin work | CSS, responsive pages, CMS experience, page-speed care |
If the job says React but the work is mostly WordPress, decide whether that is a good career move before applying. If the role says frontend engineer but the description talks about product, APIs, and ownership, prepare for deeper interviews.
For Bangalore, React is a practical default, but not the whole story. Angular remains relevant in enterprise teams, Vue appears in product and agency work, and strong JavaScript matters everywhere. Do not choose a stack from hype alone; choose it from the roles you are targeting this month.
Prepare in this order:
| Skill | Beginner proof | Experienced proof |
|---|---|---|
| JavaScript | can build search, filter, form, timer, and API widgets | can debug async bugs, stale state, race conditions, and data transforms |
| CSS | can build responsive pages with Flexbox and Grid | can fix layout bugs, overflow, stacking, theming, and design-system styles |
| React or Angular | can build complete flows | can design component boundaries and manage state safely |
| TypeScript | can type props and API responses | can model state transitions and remove unsafe assumptions |
| APIs | can fetch and render data | can handle auth, validation errors, retries, cancellation, and partial failures |
| Quality | can write simple tests | can decide which behavior needs tests and which checks belong in review |
| Performance | knows DevTools basics | can diagnose slow renders, large bundles, and expensive interactions |
If this list feels too wide, start with the Frontend Developer Roadmap. Then return to this article when you are ready to apply.
The best Bangalore portfolio is not a visual gallery. It is a proof system.
Build a dashboard that feels like something a B2B product team might ship.
Include:
What to write:
Build one of these:
Include validation, step navigation, saved progress, review screen, error summary, and success state. This helps because many actual frontend jobs involve forms, not only landing pages.
Build a small documented component set:
Show states: loading, disabled, error, focus, destructive, and empty. Add usage examples. If you are experienced, include tradeoffs around controlled/uncontrolled props, composition, and accessibility.
Your resume should tell the company why your proof matches their work. If the listing is for dashboards, lead with a dashboard project. If it is for UI implementation, lead with CSS and responsive polish. If it is for a GCC, lead with maintainability, tests, and review-ready code.
Do this:
Weak bullet:
Better bullet:
For experienced candidates:
That gives interviewers something concrete to discuss.
Do not apply randomly for two weeks and then conclude the market is bad. Run a deliberate pipeline and review it weekly.
| Step | What to do | Why it helps |
|---|---|---|
| Build a target list | 40-60 companies split by product, GCC, startup, agency, services | You stop reacting only to job boards |
| Map role types | React product, Angular enterprise, UI developer, design system, remote | You customize proof instead of blasting resumes |
| Prepare two resume variants | product/frontend engineer and UI/web developer | You do not undersell or oversell yourself |
| Send targeted notes | mention one matching project or case study | Recruiters see relevance quickly |
| Track outcomes | applied, response, test, interview, rejection reason | You learn which lane is working |
After 25-30 applications, inspect the pattern. No callbacks usually means the resume or portfolio proof is weak. Callbacks followed by failed tests usually means interview practice is the bottleneck. Interviews that end after project discussion usually mean you need clearer ownership stories.
Use How to Evaluate Companies as a Front End Engineer before accepting a role that sounds exciting but has unclear frontend ownership.
Bangalore interviews vary widely. Prepare for these patterns:
| Round | Common expectation | How to practice |
|---|---|---|
| JavaScript | arrays, objects, async, closures, event loop, DOM | timed questions and small browser exercises |
| React | state, effects, rendering, keys, forms, refs, composition | explain bugs from past projects |
| TypeScript | props, API types, unions, generics, narrowing | type a small API-backed feature |
| CSS | layout, specificity, responsive design, overflow, positioning | recreate product layouts without a UI kit |
| UI coding | build component or flow quickly | forms, tabs, modal, data table, autocomplete |
| System design | design a frontend feature at product scale | talk through state, data, caching, performance, accessibility |
| Project deep dive | prove you built the work | prepare decisions, bugs, tradeoffs, and next improvements |
Practice React interview questions, JavaScript interview questions, Data Table, Contact Form, Autocomplete, and File Explorer.
Freshers need proof that they can be onboarded quickly.
Do this:
Avoid filling your resume with advanced tools before you can explain JavaScript, CSS layout, and React state.
Read Frontend Developer Jobs for Freshers: How to Get Your First Role in 2026 for a full fresher path.
If you already have experience, your job search should center on scope.
Prepare examples for:
Your portfolio can use anonymized case studies. You do not need to expose private company code. You do need to explain what you owned.
Watch for:
Not every imperfect role is bad. Early-career roles can be messy and still useful. But know what tradeoff you are accepting.
Bangalore frontend developer jobs in 2026 reward targeted proof. Pick a role lane, build projects that match it, prepare JavaScript and UI coding seriously, and make each application about the frontend problems the company actually has.

Frontend developer jobs in Hyderabad are a good fit if you can build maintainable web apps, work with backend and design teams, and prove React, Angular, TypeScript, API, and UI debugging skill.
The important word is "maintainable." Hyderabad has startups, service companies, SaaS teams, media companies, fintech teams, cloud products, and large product engineering centers. Many frontend roles sit inside bigger engineering systems, so companies care about code that other people can read, review, test, and extend.
That changes your preparation. A flashy personal site helps only a little. A project that handles form validation, role-based screens, table state, API failures, and responsive layout says much more.
Use global stack data carefully. The 2025 Stack Overflow Developer Survey still shows JavaScript, HTML/CSS, TypeScript, React, Next.js, and Angular as common professional-developer technologies. That supports preparing those skills, but the exact framework still depends on the Hyderabad role: enterprise teams may be Angular-heavy, product teams may be React-heavy, and web roles may still ask for CMS or plain JavaScript work.
The same title can hide different jobs. Read the job description before deciding whether to apply.
| Job title pattern | What the work often means | How to prove fit |
|---|---|---|
| Front End Developer | General website or app UI work, often HTML, CSS, JavaScript, Bootstrap, WordPress, React, or Angular | Show polished UI, responsive layout, and basic interaction quality |
| ReactJS Developer | Product screens, dashboards, state, API integration, reusable components | Show React projects with forms, routing, async states, and TypeScript |
| Angular Developer | Enterprise apps, admin tools, forms, services, reusable modules | Show typed forms, validation, API services, and component structure |
| Front-End UI Developer | CSS-heavy implementation, design handoff, browser behavior, layout details | Show pixel-careful pages, responsive states, and accessibility basics |
| Senior Frontend Developer | Architecture, review, mentoring, performance, migration, design system work | Show case studies, tradeoffs, and production ownership |
| Frontend Intern or Fresher | Small components, bug fixes, HTML/CSS/JS tasks, simple framework work | Show two finished projects and clean GitHub repos |
Do not apply to all of these with the same resume. A WordPress-heavy role, a React product role, and an Angular enterprise role need different evidence. The fastest way to waste applications is to send a React-only resume to a UI/CSS role or a beginner project gallery to a maintainability-heavy enterprise role.
Think of the city as several markets, not one market.
| Company type | What they usually test | Good candidate signal |
|---|---|---|
| GCCs and multinational product teams | maintainability, code review, TypeScript, process, collaboration | You can explain component boundaries and edge states |
| SaaS and B2B product companies | dashboards, workflows, API integration, customer-facing product UI | You have built product flows, not only landing pages |
| Service companies | adaptability across clients, fast delivery, stack flexibility | You know one framework well and can pick up adjacent tools |
| Media and creator-tech companies | responsive UI, speed, web publishing, visual polish | You can build attractive pages without breaking performance |
| Fintech and operations products | tables, forms, permissions, audit-like flows, reliability | You handle validation, disabled states, and failure recovery |
| Early startups | broad ownership, quick iteration, debugging across the stack | You can clarify requirements and ship a small feature end to end |
If you are a fresher, your first target can be internships, trainee roles, junior UI roles, or small-company frontend roles. If you have 2-4 years of experience, aim for product UI roles where React or Angular is central. If you have 5+ years, look for roles that mention ownership, architecture, performance, design systems, or mentoring.
The Hyderabad list should not be read as a permanent ranking. It is a practical target map. Check current openings, team scope, and interview expectations before applying.
| Company group | Examples to research | Frontend angle to look for |
|---|---|---|
| Large product and platform companies | Microsoft, Google, Amazon, Salesforce, ServiceNow, Oracle, Qualcomm, Apple | large engineering systems, enterprise UI, internal platforms, cloud tools, product workflows |
| Finance, operations, and enterprise GCCs | Wells Fargo, JPMorgan Chase, Deloitte, EY, UBS, State Street, The Hartford | dashboards, forms, approvals, role-based UI, compliance-heavy workflows |
| SaaS, media, and product engineering teams | ValueLabs, EPAM, OpenText, Model N, Electronic Arts, Ivy | product screens, analytics UI, customer tools, design and backend collaboration |
| IT services and consulting companies | Accenture, Infosys, TCS, Cognizant, Capgemini, Tech Mahindra, Wipro | client apps, migrations, Angular/React delivery, frontend maintenance, broader stack exposure |
| Startups and local product teams | T-Hub ecosystem companies, fintech, healthtech, edtech, creator-tech teams | broader ownership, faster learning, product ambiguity, smaller frontend teams |
For freshers, do not apply only to famous names. Hyderabad has many smaller teams where a junior developer can get more frontend reps. For experienced developers, prioritize teams that mention product ownership, design systems, performance, testing, or platform work.
Before shortlisting a company, check whether the role describes the product surface, review process, and frontend ownership. A job post that says only "React, HTML, CSS, JavaScript" may still be useful, but you need to ask what you will actually build.
Do not begin by collecting every framework name. Prepare the skill stack that appears across many Hyderabad roles.
| Skill | What interviewers may ask | What to build |
|---|---|---|
| HTML and CSS | forms, semantic tags, responsive layout, Flexbox, Grid, specificity, overflow | settings page, pricing page, form flow, dashboard shell |
| JavaScript | arrays, objects, promises, closures, event handling, fetch, timers | search page, filterable table, debounced input, polling widget |
| React or Angular | state, props, effects or lifecycle, forms, routing, reusable components | customer dashboard, ticket system, onboarding form |
| TypeScript | props, API response types, unions, narrowing, event types | typed API client, typed form state, typed table rows |
| APIs | loading, empty, error, retry, auth failure, validation errors | API-backed dashboard with realistic failure states |
| Testing | user behavior, form submission, async UI, simple component tests | tests for filter, form, and save flows |
| Accessibility | labels, focus order, keyboard navigation, modal behavior, error text | keyboard-safe form, dialog, tabs, or menu |
| Performance | large lists, image loading, render cost, network waterfall | table with pagination, optimized image page, measured interaction |
Use the Frontend Developer Roadmap if you need a broader order. For this article, the practical target is simple: be able to build a useful product screen and explain why it works.
Job descriptions often mix must-haves, nice-to-haves, and recruiter filler. Translate them into actual preparation.
| JD phrase | What it probably means | What to prepare |
|---|---|---|
| "Collaborate with designers and backend developers" | You will receive designs and API contracts that are not always perfect | Practice asking API, loading, validation, and responsive questions |
| "Responsive web applications" | CSS and browser behavior matter | Build layouts that work at mobile, tablet, and desktop sizes |
| "Reusable components" | They care about maintainability | Prepare examples of component props, naming, and composition |
| "React and Next.js" | They may expect routing, rendering, data loading, and app structure | Build a route-based app, not only isolated components |
| "Angular/React" | The team may support older or mixed codebases | Show framework basics plus solid JavaScript |
| "Enterprise user interfaces" | Forms, tables, permissions, audit flows, and long-lived code | Build admin-style workflows with edge states |
| "Performance" | They may have slow pages, large lists, or heavy dashboards | Learn how to inspect renders, bundles, images, and network requests |
If a JD lists 20 technologies, do not panic. Find the work behind the list. Is it product UI? CMS work? enterprise dashboard work? migration work? Your application should answer that need.
Build projects that look like actual frontend work inside teams.
Include:
Write a project note explaining why filters live in the URL, how you avoid duplicate state, and what happens when the API fails.
Good examples:
Include:
This project helps because Hyderabad roles often involve form-heavy enterprise UI. A careful multi-step flow is better than another weather app because it reveals how you handle validation, recovery, keyboard use, and state across screens.
Include:
This shows product judgment. Many candidates can render a button. Fewer can explain who should be allowed to press it and what happens when the save fails.
Your resume should change with your level.
| Level | What the resume should prove | Example bullet |
|---|---|---|
| Fresher | You can finish small frontend projects and explain them | Built a React onboarding form with validation, review step, saved progress, and mobile layout |
| 1-2 years | You can deliver scoped features with review | Built reusable table filters and API error states for an internal dashboard |
| 3-5 years | You can own a product flow | Owned a customer settings flow across React components, API integration, validation, and release fixes |
| 5+ years | You can reduce technical and product risk | Led a frontend refactor that simplified state ownership and reduced repeated form bugs across three screens |
Weak resume bullets name tools. Better bullets name behavior.
Weak:
Better:
If your resume does not give an interviewer a concrete question to ask, rewrite it.
Not every company runs the same process, but Hyderabad frontend interviews often include these patterns:
| Round | What they are checking | How to prepare |
|---|---|---|
| Screening call | role fit, salary range, notice period, stack match | Have a 30-second summary and target role clear |
| JavaScript round | language basics and debugging | Practice arrays, promises, closures, object transforms, and async mistakes |
| Framework round | React or Angular depth | Prepare forms, state, lifecycle/effects, routing, reusable components |
| UI coding | can you build under time pressure | Practice forms, tabs, data table, autocomplete, modal, accordion |
| Project discussion | did you actually build the work | Prepare tradeoffs, bugs, constraints, and improvements |
| Hiring manager round | team fit and ownership | Explain how you clarify requirements and handle review feedback |
Practice JavaScript interview questions, React interview questions, and UI tasks such as Data Table, Contact Form, and Transfer List.
If you are targeting Angular roles, practice the same behavior in Angular: forms, validation, API state, component inputs/outputs, services, and routing.
Use this if you already know basic HTML, CSS, JavaScript, and one framework.
| Days | Work |
|---|---|
| 1-4 | Fix JavaScript gaps: arrays, objects, promises, closures, fetch, and event handling |
| 5-8 | Build or improve a form-heavy project with validation and accessibility checks |
| 9-13 | Build an API-backed dashboard with filters, loading, empty, error, and retry states |
| 14-17 | Add TypeScript to one project and remove unsafe any |
| 18-20 | Write READMEs and case notes for your best projects |
| 21-24 | Practice UI coding tasks under a timer |
| 25-27 | Rewrite resume bullets for Hyderabad role types |
| 28-30 | Apply to a targeted list and record interview feedback |
If the first two weeks produce no responses, do not add another certificate first. Check whether your strongest project is visible in the first half of the resume, whether the live link works, and whether the bullets match the role type.
Do not wait until day 30 to apply if you already have decent proof. Start applying once your best project is deployed and readable.
Ask questions that reveal the actual frontend work:
These questions help you avoid roles where the title sounds good but the work does not match your goal.
Hyderabad frontend developer jobs in 2026 reward candidates who can work inside larger product systems. Prepare the framework, but make your proof about maintainable UI: forms, tables, API states, TypeScript, review-ready code, and clear ownership.

To learn React in 2026, learn components, JSX, props, state, rendering, effects, forms, and data flow before you chase framework features. Then build enough UI that you can decide what belongs in local state, URL state, server state, or a parent component.
React is easier when JavaScript already feels familiar. If arrays, objects, functions, promises, and modules still feel shaky, spend time on JavaScript first.
| Stage | What to learn | What to practice |
|---|---|---|
| 1 | Components and JSX | Break a page into reusable pieces |
| 2 | Props and composition | Pass data down without duplicating UI |
| 3 | State and rendering | Build counters, toggles, tabs, accordions |
| 4 | Events and forms | Controlled inputs, validation, submit flows |
| 5 | Effects | Sync with browser APIs and external systems |
| 6 | Data fetching | Loading, empty, error, retry, stale responses |
| 7 | Routing and app structure | Multi-page product flows |
| 8 | TypeScript and testing | Safer props, user-focused tests |
The official React Learn docs are organized around the concepts beginners use daily: components, markup, data display, conditions, lists, events, state, Hooks, and sharing data between components. Use that sequence as your spine.
A React component is a function that returns UI. The hard part is not writing the function. The hard part is deciding the boundary.
Good beginner components usually answer one of these questions:
Start with static components:
function ProfileCard({ name, role }: { name: string; role: string }) {return (<article><h2>{name}</h2><p>{role}</p></article>);}
Then practice rendering lists, conditional UI, and nested components. Avoid splitting everything into tiny files too early. A component boundary should make the code easier to read or change.
Props are input. State is memory. Beginners often reach for state too quickly.
Use props when a component can be fully described by data from its parent:
function Price({ amount }: { amount: number }) {return <span>${amount.toFixed(2)}</span>;}
Use state when the component needs to remember something that changes because of user interaction, time, network responses, or browser state.
Ask this before adding state:
Derived state bugs are common in interviews and code reviews. If fullName can be calculated from firstName and lastName, calculate it during render instead of storing another state variable.
React rendering is a mental model, not only a syntax topic. A state update schedules a new render. During that render, React calls the component again and calculates the next UI.
Practice these cases:
When a new state value depends on the previous one, practice the updater form:
setCount((count) => count + 1);
That habit matters for event handlers that queue multiple updates, async callbacks, and components where several interactions can happen quickly.
For arrays, use IDs as keys when possible. Index keys are risky when users can insert, remove, sort, or filter items because React may preserve state for the wrong item.
Forms teach most of React's daily skills in one place: state, events, validation, async work, disabled states, error messages, and accessibility.
Build a signup form with:
Do not stop at alert("submitted"). Real forms fail. Users type invalid data. Networks slow down. Servers reject requests. A job-ready React developer knows how the UI behaves in each state.
useEffect is not the place to put every calculation. Use it when the component must sync with something outside React: the document title, a browser API, a subscription, a timer, or an imperative library.
Many beginner bugs come from unnecessary effects:
// Avoid storing derived data in state with an effect.const completedCount = todos.filter((todo) => todo.done).length;
If you can calculate a value during render, do that. If an effect starts a subscription, timer, request, or event listener, think about cleanup.
React itself does not prescribe one data fetching library for every app. Your learning goal is to understand the states around data:
Build a small search page and handle out-of-order responses:
import { useRef, useState } from 'react';type Product = {id: string;name: string;};function ProductSearch() {const [products, setProducts] = useState<Product[]>([]);const [status, setStatus] = useState<'idle' | 'loading' | 'error'>('idle');const latestRequestId = useRef(0);async function searchProducts(query: string) {const requestId = ++latestRequestId.current;setStatus('loading');try {const response = await fetch(`/api/products?q=${encodeURIComponent(query)}`,);const data = await response.json();if (requestId !== latestRequestId.current) {return;}setProducts(data.products);setStatus('idle');} catch {if (requestId === latestRequestId.current) {setStatus('error');}}}// Render the form, status message, and product list here.}
In a real app, a library may handle caching and request state for you. The interview skill is explaining the failure mode: an older request should not overwrite newer results. In production code, also consider AbortController so the browser can cancel work that is no longer needed.
After you can build React components and flows, learn routing. For many production apps in 2026, that means learning React through a framework such as Next.js, Remix, or React Router-based setups.
Learn these routing concepts:
If you choose Next.js, learn App Router concepts after React basics: Server Components, Client Components, layouts, route handlers, metadata, caching, and revalidation.
TypeScript helps you make component contracts explicit:
type ProductCardProps = {id: string;name: string;price: number;onAddToCart: (id: string) => void;};function ProductCard({ id, name, price, onAddToCart }: ProductCardProps) {return (<article><h2>{name}</h2><p>${price.toFixed(2)}</p><button onClick={() => onAddToCart(id)}>Add to cart</button></article>);}
Start with props, event handlers, form state, API response types, and union types for UI states. Avoid learning the deepest generic patterns before you can type ordinary components well.
Read TypeScript for React Developers when you want a focused bridge from React to TypeScript.
| Project | What it proves |
|---|---|
| Todo app with filters | State updates, derived data, forms |
| Product listing page | Lists, API fetching, loading, empty and error states |
| Multi-step form | Validation, state transitions, accessibility |
| Dashboard widgets | Component composition and data formatting |
| File explorer | Recursion, tree data, selection state |
| Autocomplete | Async search, keyboard interaction, stale-response handling |
For interview prep, practice React interview questions and UI tasks such as Tabs, Accordion, and Data Table.
The first mistake is treating React as magic. React is still JavaScript. If a callback receives stale data, if an array is mutated, or if a promise resolves late, React will expose that mistake.
The second mistake is putting all state in one place. Local UI state should often stay local. Server data should not be manually copied into many unrelated components. URL state belongs in the URL when the user expects refresh, share, or back-button behavior to preserve it.
The third mistake is learning Hooks as a list of APIs instead of learning why they exist. useState stores component memory. useEffect syncs with external systems. useMemo and useCallback are tools for specific rendering and identity problems, not default wrappers for every value.
The fourth mistake is using effects to mirror state. If filteredProducts can be calculated from products and query, calculate it during render or with useMemo when the calculation is actually expensive. Storing it separately creates another value that can go stale.
| Weeks | Plan | Output |
|---|---|---|
| 1-2 | Components, JSX, props, conditional rendering, lists | Static product page and reusable cards |
| 3-4 | State, events, forms, validation | Signup form and todo app |
| 5-6 | Effects, browser APIs, data fetching | API search page with full request states |
| 7 | Routing and URL state | Product listing with filters in the URL |
| 8 | TypeScript with React | Typed component library for your projects |
| 9 | Testing and accessibility | User-focused tests and keyboard behavior fixes |
| 10 | Interview practice and portfolio cleanup | Two projects explained clearly in READMEs |
You are job-ready for beginner React roles when you can build a small product flow, explain your component boundaries, handle failure states, and debug why the UI rendered the way it did.

The practical way to learn TypeScript in 2026 is to use it to make JavaScript contracts visible: function inputs, return values, object shapes, component props, API responses, and impossible UI states.
TypeScript is not a replacement for JavaScript. The TypeScript Handbook describes it as a static typechecker for JavaScript programs: it runs before your code and checks whether the types line up. That means JavaScript knowledge still comes first.
| Stage | What to learn | What it helps you prevent |
|---|---|---|
| 1 | Basic annotations and inference | Passing the wrong value type |
| 2 | Object types and interfaces | Missing or misspelled properties |
| 3 | Unions and narrowing | Unsafe access to values that may differ |
| 4 | Functions and callbacks | Wrong handler signatures |
| 5 | Generics | Reusable utilities without losing types |
| 6 | React and API types | Weak component and server contracts |
| 7 | Compiler options | Hidden any, null, and module mistakes |
Use the official TypeScript Handbook as your reference. It is designed for everyday programmers and covers the concepts you need before the more formal reference material.
TypeScript can infer many types from values:
const count = 0;const title = 'JavaScript Roadmap';const tags = ['javascript', 'react'];
You do not need to annotate those. Over-annotation makes code noisy and can hide the real contract.
Add types where they clarify a boundary:
function formatPrice(amount: number, currency: string): string {return new Intl.NumberFormat('en', {style: 'currency',currency,}).format(amount);}
The useful question is: "Where could another developer call this incorrectly?" Those places deserve explicit types.
Frontend code passes objects everywhere: API data, component props, form values, config, route params, and analytics events.
Start with object types:
type Product = {id: string;name: string;price: number;inStock: boolean;};function getDisplayName(product: Product) {return product.inStock ? product.name : `${product.name} (sold out)`;}
Learn optional properties carefully:
type User = {id: string;name: string;avatarUrl?: string;};
avatarUrl?: string means the property may be missing or undefined. Your UI needs a fallback before rendering an image.
Union types let you model choices:
type RequestState =| { status: 'idle' }| { status: 'loading' }| { status: 'success'; products: Product[] }| { status: 'error'; message: string };
This is more accurate than several booleans such as isLoading, hasError, and data, which can drift into impossible combinations.
Use narrowing to safely read the right fields:
function ProductResults({ state }: { state: RequestState }) {if (state.status === 'loading') {return 'Loading products...';}if (state.status === 'error') {return state.message;}if (state.status === 'success') {return `${state.products.length} products`;}return 'Search for a product';}
This pattern is useful in React, reducers, data fetching, form flows, and interview answers.
For larger unions, add an exhaustiveness check so future states cannot be forgotten silently:
function assertNever(value: never): never {throw new Error(`Unhandled state: ${JSON.stringify(value)}`);}function getStatusText(state: RequestState) {switch (state.status) {case 'idle':return 'Search for a product';case 'loading':return 'Loading products...';case 'success':return `${state.products.length} products`;case 'error':return state.message;default:return assertNever(state);}}
This is one of TypeScript's best frontend uses: the compiler helps you update all UI branches when a product state changes.
Many TypeScript bugs show up at function boundaries.
Practice typing:
Example:
type SaveProduct = (product: Product) => Promise<{ id: string }>;async function submitProduct(product: Product, saveProduct: SaveProduct) {const result = await saveProduct(product);return result.id;}
Do not use Function as a type. It throws away the contract. Name the parameters and return value.
Generics are for reusable code where the input and output types are connected.
function groupBy<T>(items: T[],getKey: (item: T) => string,): Record<string, T[]> {return items.reduce<Record<string, T[]>>((groups, item) => {const key = getKey(item);groups[key] ??= [];groups[key].push(item);return groups;}, {});}
The generic T keeps the item type through the function. If you pass Product[], the grouped values are still Product[].
Learn generics through small utilities before reading advanced type puzzles. Most frontend work needs clear generic functions, not clever type gymnastics.
Also learn satisfies for configuration objects. It checks that an object matches a type without throwing away the object's specific literal values:
type RouteConfig = Record<string, { title: string; requiresAuth: boolean }>;const routes = {home: { title: 'Home', requiresAuth: false },dashboard: { title: 'Dashboard', requiresAuth: true },} satisfies RouteConfig;
That is useful for design tokens, route maps, analytics event maps, and component variant configs.
TypeScript is especially useful for React props:
type ButtonProps = {children: React.ReactNode;variant: 'primary' | 'secondary';disabled?: boolean;onClick: () => void;};function Button({ children, variant, disabled, onClick }: ButtonProps) {return (<button data-variant={variant} disabled={disabled} onClick={onClick}>{children}</button>);}
This contract prevents invalid variants and makes the expected click behavior clear.
For React projects, learn:
TypeScript for React Developers is the better next step if your main goal is frontend work.
TypeScript can be weak or strict depending on your configuration. A project with too many any values gives less protection than it appears to.
Learn these options early:
strictnoImplicitAnystrictNullChecksnoUncheckedIndexedAccessexactOptionalPropertyTypesYou do not need every strict option on day one in an existing codebase. For a learning project, turn on strict and fix the errors. The compiler feedback is part of the lesson.
The best TypeScript project is not a blank file with type examples. Take a small JavaScript app and migrate it.
Good migration order:
.js to .ts and .jsx to .tsx.any values.Migration teaches you what TypeScript actually catches: misspelled fields, missing null checks, inconsistent return values, invalid component props, and weak API assumptions.
The first mistake is using any to silence the compiler. If a value is genuinely unknown, use unknown, validate or narrow it, then use it.
The second mistake is typing the wrong boundary. Typing every local variable is less useful than typing the API response, public function, or component prop.
The third mistake is believing TypeScript validates runtime data. It does not. If JSON comes from a server, TypeScript can describe what you expect, but runtime validation is still needed when the data is untrusted.
The fourth mistake is overusing advanced types. If nobody on the team can read the type, it may cost more than it saves. Prefer types that make product states and code contracts easier to understand.
The fifth mistake is treating generated API types as proof that the backend can never send bad data. Generated types are valuable, but a network boundary is still a runtime boundary. Validate user-controlled data, third-party API responses, webhooks, and anything that can drift independently of your frontend deploy.
| Week | Plan | Output |
|---|---|---|
| 1 | Inference, annotations, object types | Typed utility functions |
| 2 | Arrays, records, optional properties | Typed data transformation exercises |
| 3 | Unions, narrowing, discriminated unions | Request-state and form-state models |
| 4 | Functions, callbacks, async types | Typed API and event-handler examples |
| 5 | Generics and reusable utilities | groupBy, pick, sortBy, typed fetch wrapper |
| 6 | React or project migration | One JavaScript project converted to TypeScript |
You have learned TypeScript well enough for junior frontend work when you can type component props, API responses, event handlers, utility functions, and UI states without reaching for any as your default escape hatch.

Frontend developer jobs for freshers are possible in 2026, but a certificate is not enough. You need finished projects, clean GitHub repos, interview basics, and proof that you can complete small UI tasks.
The fresher market is crowded because many candidates look identical on paper: HTML, CSS, JavaScript, React, one course certificate, two cloned projects. Your job is to make the hiring team believe you can be onboarded into a real codebase and improve with review.
That does not require pretending to be senior. It requires specific proof. A hiring team should be able to open your portfolio and see, within two minutes, that you can build a form, handle data, write readable code, and explain one project without hiding behind course language.
The stack does not need to be exotic. The 2025 Stack Overflow Developer Survey still shows JavaScript, HTML/CSS, TypeScript, React, Next.js, and Angular as widely used among professional developers. For a fresher, that is a reason to learn the web basics deeply before chasing every new library.
Most fresher frontend roles do not expect architecture ownership. They expect a beginner who can learn quickly and avoid careless mistakes.
| Expectation | What it means in practice | How to prove it |
|---|---|---|
| HTML and CSS basics | Can build a page from a design and make it responsive | Build a polished responsive page with forms and states |
| JavaScript basics | Can handle user interaction and data changes | Build search, filter, timer, and API widgets |
| Framework basics | Can write simple React, Angular, or Vue components | Build a small product flow, not only a counter app |
| GitHub hygiene | Can share code for review | Add READMEs, live links, and clean project structure |
| Debugging attitude | Can inspect errors instead of guessing | Use DevTools and explain one bug you fixed |
| Communication in review | Can ask questions and respond to feedback | Write clear project notes and resume bullets |
Freshers lose interviews when they list too many tools and cannot explain the basics. Keep your skill list honest. If you wrote a project by following a tutorial, be ready to explain what you changed and which part you would rebuild differently.
Your first frontend role may not be titled exactly "frontend developer." Search across related titles.
| Role title | Good fit if | What to prepare |
|---|---|---|
| Frontend Developer Fresher | You have HTML, CSS, JS, and one framework project | portfolio, JavaScript basics, React or Angular basics |
| Frontend Intern | You are still learning and need supervised work | clean projects, learning attitude, availability |
| Web Developer Fresher | You are good with HTML, CSS, basic JS, CMS, or websites | responsive pages, forms, visual polish |
| UI Developer Trainee | You like layout and implementation from designs | CSS, browser behavior, accessibility basics |
| React Developer Intern | You have React projects and can explain state | React forms, lists, effects, API states |
| Full Stack Fresher | You know some backend too | basic frontend plus API and database fundamentals |
Do not reject a good internship because the title is not perfect. Your first role is about getting credible experience, feedback, and team exposure. A paid internship with code review can be more useful than a "frontend developer" title where nobody reviews your work.
Use this order. It keeps you from building a React app while still being weak at browser basics.
| Stage | Learn | Practice task |
|---|---|---|
| 1 | HTML structure, forms, labels, buttons, links, tables | build an accessible contact or signup form |
| 2 | CSS layout, Flexbox, Grid, responsive design, focus states | recreate a dashboard or settings page |
| 3 | JavaScript values, functions, arrays, objects, DOM, events | build search, filter, modal, tabs, accordion |
| 4 | Async JavaScript, fetch, promises, errors | build an API-backed search page |
| 5 | React or Angular basics | build a form-heavy product flow |
| 6 | Git, GitHub, deployment, README | publish projects and make them reviewable |
| 7 | Interview practice | solve JavaScript and UI tasks under time |
Use How to Become a Frontend Developer if you need a full roadmap before this job-search plan.
Do not build ten small clones. Build three projects that prove different frontend skills. Each project should have a deployed link, a GitHub repo, a README, and one short note explaining a decision you made.
Build one of these:
Include:
What it proves: forms, validation, state, accessibility, and attention to user mistakes.
What interviewers may ask:
Build one of these:
Include:
What it proves: async JavaScript, API handling, state changes, and user feedback.
What interviewers may ask:
Build one of these:
Include:
What it proves: state modeling, derived values, and product behavior.
What interviewers may ask:
Read How to Build a Frontend Developer Portfolio With No Experience (2026) for a deeper portfolio guide.
A fresher with clean GitHub is easier to review because many beginner repos are hard to run.
For each project:
README structure:
# Project NameShort description.## Live demoLink## Features- Search by keyword- Loading and error states- Responsive layout## Tech stackReact, TypeScript, CSS## Run locallynpm installnpm run dev## What I learnedOne or two specific lessons.
If your repo has no README, a reviewer has to work too hard. Do not make that their first impression. Also check that npm install and the documented run command work from a fresh clone; broken setup quietly kills many beginner applications.
Keep the resume simple and proof-heavy.
Recommended order:
Good headline:
Frontend developer fresher with React projects, JavaScript practice, and deployed UI work.
Weak headline:
Highly motivated individual seeking an opportunity.
Project bullet formula:
Built [project] using [stack] with [specific frontend behavior].
Examples:
Do not rely only on job boards.
Use five channels:
| Channel | How to use it |
|---|---|
| Job boards | Apply to fresher, intern, trainee, web developer, UI developer, and React intern roles |
| Company career pages | Apply directly when the role matches your project proof |
| Referrals | Send a specific project link and resume, not a vague request |
| LinkedIn posts | Reply early with a short note and portfolio link |
| Local/startup communities | Look for internships and small product teams |
Application note:
Hi [Name],I am applying for the frontend intern role. I built a React onboarding form with validation, review step, and responsive layout: [link].My portfolio and GitHub are here: [links].
Keep it short. The project link does the work. Do not attach five projects. Send the one that matches the role and make the next click obvious.
Prepare for four types of questions.
Practice:
async/awaitPractice:
For React:
For Angular:
Prepare answers for:
Practice JavaScript interview questions, React interview questions, Contact Form, Tabs, and Accordion.
| Days | Work |
|---|---|
| 1-7 | Fix HTML, CSS, JavaScript basics with small exercises |
| 8-18 | Build multi-step form and deploy it |
| 19-30 | Build API-backed search page and deploy it |
| 31-40 | Build cart, booking, or expense tracker |
| 41-45 | Clean GitHub, READMEs, screenshots, and live links |
| 46-50 | Build portfolio site and write project notes |
| 51-55 | Rewrite resume and LinkedIn profile |
| 56-60 | Apply daily and practice interview questions |
After day 60, do not disappear into another course. Keep applying, review interview feedback, and improve the weakest part of your proof.
Add one maintenance habit while applying: every Friday, open your own live links, run the projects locally, and fix one confusing README or UI state. A small broken detail can make a careful beginner look careless.
Avoid:
Your first job search is not about proving you know everything. It is about proving you can learn inside a team and finish small frontend work carefully.
Frontend developer jobs for freshers go to candidates who make their ability visible. Build three finished projects, clean up GitHub, write concrete resume bullets, and practice the basics until you can explain your own code calmly.

The best way to learn JavaScript in 2026 is to learn the language, then use it in the browser, then practice enough small programs that callbacks, promises, objects, arrays, and DOM updates stop feeling separate.
Do not start by memorizing every method on Array. Start by learning what runs, when it runs, what data changes, and what the page should show after each change.
| Stage | What to learn | What you should be able to build |
|---|---|---|
| 1 | Syntax, values, variables, functions | Small console programs |
| 2 | Arrays, objects, strings, dates, maps, sets | Data transformation utilities |
| 3 | Control flow and error handling | Input validation and retry logic |
| 4 | DOM, events, forms, accessibility basics | Interactive browser widgets |
| 5 | Async JavaScript, promises, fetch() | API-backed pages |
| 6 | Modules, tooling, linting, tests | Maintainable mini apps |
| 7 | Interview patterns and debugging | Explain and fix unfamiliar code |
MDN's JavaScript Guide is the best primary reference for the language because it covers grammar, control flow, functions, objects, promises, modules, and browser-facing usage in one place. Use it as reference material, not as a book you must finish before building.
Start with JavaScript as a programming language before jumping into React, Next.js, or Node.js.
Learn these topics in order:
null, undefined, objects, arraysconst, let, scope, reassignmentif, switch, loops, early returnstry, catch, throwing useful errorsThe goal is not trivia. The goal is to predict what a piece of code will do without running it.
For example, a beginner should be able to explain why this produces a new array and does not mutate prices:
const prices = [100, 200, 300];const discounted = prices.map((price) => price * 0.9);
That skill matters more than knowing ten array methods by name.
Most frontend work is data shaping. You receive API data, user input, configuration, or component props, then turn it into UI.
Practice with small exercises:
" React Developer " into "react developer"This is where methods like map, filter, find, some, every, reduce, sort, slice, toSorted, and Object.entries become useful.
Two details matter while practicing:
toSorted() where your browser support target allows it, or copy with [...items].sort(...) before sorting.=== is usually the default; == has coercion rules that are useful to understand but easy to misuse.Use GreatFrontEnd JavaScript interview questions when you want targeted practice. Interview-style questions are useful even before interviews because they force you to reason through edge cases.
Frontend JavaScript runs inside a browser. That means you need the DOM, events, forms, accessibility, layout interactions, storage, network requests, and browser limitations.
Build these without a framework first:
The important part is the connection between state and UI. When data changes, what should change on the page? When the user clicks, types, submits, or presses a key, which code should run?
Do not skip accessibility while learning DOM work. A button should be a button. A label should be connected to its input. Error text should be reachable by assistive technology. These habits are easier to learn early than to patch later.
Async JavaScript is where many beginners get stuck because the code does not run top to bottom in the way they expect.
Learn these concepts together:
async and awaitfetch()AbortControllerBuild a search page that calls an API when the user submits a query. Then add:
That one project teaches more useful async JavaScript than many syntax-only exercises.
For example, a plain JavaScript search flow can combine AbortController with a current-request check:
let currentController;async function runSearch(query) {currentController?.abort();const controller = new AbortController();currentController = controller;try {const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {signal: controller.signal,});const results = await response.json();if (controller !== currentController) {return;}renderResults(results);} catch (error) {if (error.name !== 'AbortError') {renderError('Search failed. Try again.');}}}
This is not only an API trick. It teaches the habit of asking which async result is still allowed to update the UI.
Do not install a build tool on day one. Wait until you feel the problem it solves.
You are ready for tooling when:
At that point, learn npm scripts, package installation, ES modules, Prettier, ESLint, and a test runner such as Vitest. You do not need to become a tooling expert, but you should understand what runs when you type npm run dev, npm test, or npm run build.
A good beginner project proves behavior, not only visual polish.
| Project | Skills it proves |
|---|---|
| Expense tracker | Forms, arrays, derived totals, validation |
| Weather app | fetch(), loading, errors, empty states |
| Kanban board | Drag behavior, state updates, persistence |
| Product filter page | URL state, sorting, filtering, responsive UI |
| Quiz app | Timers, scoring, state transitions |
| GitHub profile viewer | API calls, error handling, conditional rendering |
For each project, write a short README with:
That README trains you to explain technical work, which helps in interviews and portfolio reviews.
Add one small testable rule to every project. For an expense tracker, test that deleting an item updates the total. For a search page, test that the empty state appears when the API returns no results. You do not need a giant test suite as a beginner, but you should learn that behavior can be checked without clicking through the whole app by hand.
You do not need to master all JavaScript before React, but you should be comfortable with functions, arrays, objects, modules, async code, and DOM events first.
If you start React too early, every problem feels like a React problem. Many are JavaScript problems:
JavaScript gives you the mental model. React gives you a component model for building larger interfaces.
| Weeks | Plan | Output |
|---|---|---|
| 1-2 | Syntax, functions, arrays, objects | 30 small console exercises |
| 3-4 | DOM, events, forms | Counter, todo app, form validation |
| 5-6 | Async JavaScript and APIs | Search page with loading and error states |
| 7-8 | Modules, tooling, tests | Refactor one project into modules and add tests |
| 9-10 | Browser APIs and accessibility | Modal, tabs, local storage, keyboard behavior |
| 11-12 | Interview-style practice and portfolio cleanup | Two polished projects and JavaScript question practice |
Adjust the pace if you work or study full time. The sequence matters more than the calendar.
The first mistake is copying tutorials without changing the requirements. After finishing a tutorial, add one feature without instructions.
The second mistake is learning syntax without debugging. Use browser DevTools, breakpoints, console inspection, network logs, and error messages. Debugging is part of learning the language.
The third mistake is skipping edge cases. A form with only the happy path is unfinished. What happens with empty input, slow network, invalid data, duplicate clicks, or a user using only the keyboard?
The fourth mistake is treating interviews as separate from learning. Many interview questions test the same habits you need in product code: data transformation, async control, DOM behavior, and careful explanation.
You are ready for React, TypeScript, or deeper frontend work when you can:
map, filter, and reduce without guessingLearning JavaScript in 2026 is not about finishing every topic. It is about building the mental model that lets you read unfamiliar code, predict behavior, and turn browser events into correct UI.

A frontend developer portfolio should prove that you can build useful interfaces, explain your decisions, and handle the messy parts of frontend work: state, data, accessibility, performance, errors, and product tradeoffs.
The goal is not to collect pretty screenshots. A strong portfolio makes it easy for a hiring team to see what you can be trusted to own next.
If you have no experience yet, start with How to Build a Frontend Developer Portfolio With No Experience. This guide is for the main portfolio decision: what to build, what to show, and how to stand out once you have projects, internships, freelance work, open-source work, or professional experience to present.
A useful portfolio also avoids a trap: it does not turn every project into a perfect success story. Reviewers trust portfolios that explain constraints, tradeoffs, bugs, and follow-up work. Perfect narratives sound less believable than specific ownership.
Your portfolio should answer these questions:
| Question | Weak answer | Stronger proof |
|---|---|---|
| What kind of frontend work do you do? | "I build web apps" | product frontend, design systems, platform, performance, or UI engineering examples |
| What scope can you own? | "I worked on features" | scoped feature, product flow, migration, shared component, or cross-team project |
| How do you make decisions? | list of tools | tradeoffs around state, data, performance, accessibility, and maintainability |
| How do you handle quality? | "I write clean code" | tests, review notes, accessibility checks, performance measurements, bug prevention |
| How do you work with teams? | "team player" | examples of design, backend, product, QA, or stakeholder collaboration |
Do not use the portfolio only as a visual resume. Use it as evidence of your judgment. A reviewer should leave with a clear idea of your likely level: junior feature contributor, mid-level feature owner, senior product engineer, design-system specialist, platform engineer, or lead.
Keep the site simple. Many candidates overbuild the shell and under-explain the work.
Use this structure:
| Section | What it should do |
|---|---|
| Home | state your frontend lane, seniority, strongest work, and contact links |
| Selected work | 2-4 detailed case studies |
| Technical notes | short notes on architecture, performance, accessibility, or testing |
| Code samples | public repos, open-source work, or simplified demos |
| Experience | roles, product areas, scope, and stack |
| Contact | email, LinkedIn, GitHub, resume |
Do not bury the case studies behind animations. A hiring manager or engineer may only spend a few minutes on the site before deciding whether to talk to you.
Put the best case study above any long bio. The first click should answer: what did you own, what was hard, and why does this work matter?
Your portfolio should match the next role you want.
| Target role | What to emphasize | What to avoid |
|---|---|---|
| Senior frontend engineer | ownership, tradeoffs, code quality, mentoring, product flows | only pretty screenshots |
| Product frontend engineer | user flows, API states, UX details, release decisions | isolated components with no product context |
| Design systems engineer | component APIs, accessibility, docs, adoption, migration | a random set of UI elements with no usage examples |
| Frontend platform engineer | tooling, build speed, testing infrastructure, migrations | only app feature work |
| Performance-focused frontend engineer | measurement, diagnosis, render cost, loading strategy | vague claims about speed |
| Remote frontend engineer | async docs, case studies, self-directed delivery | portfolio with no written explanation |
| Lead frontend engineer | technical direction, review quality, cross-team decisions | only individual implementation details |
This does not mean you need seven portfolios. It means your homepage and selected work should point toward one main story. If you want senior frontend roles, do not lead with a landing page clone. If you want design-system roles, do not hide component API decisions behind screenshots.
Project cards say what you built. Case studies show how you think.
Use this case study structure:
Problem:What product or engineering problem existed?Context:What team, user, system, or constraint mattered?My role:What did I personally own?Frontend decisions:State, data fetching, component boundaries, routing, accessibility, performance, testing.Tradeoffs:What did I choose not to do and why?Quality:How did I check the work?Result:What changed for users, the team, or the codebase?Next:What I would improve with more time.
You can write a good case study even if you cannot share numbers. Be precise about the shape of the work.
Weak:
Built a dashboard using React and TypeScript.
Better:
Owned a customer operations dashboard with URL-based filters, paginated API data, row-level actions, and retry handling. Split table state from server state so filters could be shared through links and restored after refresh.
Most experienced developers cannot share private code. That is normal.
Use one of these options:
| Constraint | Portfolio solution |
|---|---|
| Cannot show code | write an anonymized case study |
| Cannot show screenshots | recreate a simplified UI with fake data |
| Cannot name company | describe the domain and team size generally |
| Cannot share metrics | describe the user or engineering problem that improved |
| Work was team-owned | state your exact contribution honestly |
| Work was internal tooling | explain workflow, users, and constraints |
Do not invent impact. Hiring teams can usually spot inflated stories. Honest, specific ownership is stronger than fake numbers.
Better than a fake metric:
If you need public proof, build demos that mirror professional frontend challenges.
Include:
Explain state ownership and API assumptions. Include at least one failure path; experienced frontend work is often judged by what happens when the data is late, missing, invalid, or unauthorized.
Include:
Explain component API decisions. This is where experienced frontend judgment shows. For example, state which props are intentionally supported, which variants you rejected, and how keyboard behavior is handled.
Build or document:
Do not say "optimized." Say what was slow, how you measured it, and how you changed it.
Write a short technical note about:
Technical writing can be portfolio proof if it shows practical judgment.
Your code samples do not need to be huge. They need to be reviewable.
Good code samples show:
Avoid:
A strong portfolio should show that you can keep code boring where boring is better. If a sample uses an abstraction, explain the repeated problem it solves.
Quality separates useful portfolios from project galleries.
| Area | Portfolio evidence |
|---|---|
| Accessibility | keyboard path, labels, focus management, semantic HTML, modal behavior |
| Performance | what you measured, what was slow, what changed |
| Testing | which behavior deserved tests and why |
| Maintainability | component boundaries, naming, data flow, documentation |
| Product thinking | empty states, permission states, recovery paths, error copy |
| Review | how you split work, handled feedback, or improved a pattern |
You do not need to show all of this in every case study. Pick the details that matter for the work. One strong accessibility note beats a generic claim that the whole site is accessible.
Your homepage should be direct.
Good:
Senior frontend engineer focused on React, TypeScript, design systems, and data-heavy product UI.
Good:
Frontend engineer building accessible dashboards, form-heavy workflows, and maintainable component systems.
Weak:
I create beautiful digital experiences that delight users.
The weak version could describe almost anyone. The good versions help a hiring team place you.
Before sharing the portfolio:
Send the portfolio to one engineer and ask: "What role do you think this portfolio is targeting?" If they cannot tell, tighten the story.
Avoid:
The point is not to impress everyone. It is to make the right hiring team trust you faster.
Before sending the portfolio, read it like a skeptical interviewer:
A frontend developer portfolio should prove scope. Show what you owned, how you made decisions, how you checked quality, and why your frontend work made the product, user flow, or codebase better.

To build a frontend developer portfolio with no experience, create a simple portfolio site, add three finished projects, write project notes, deploy everything, and make your GitHub easy to review.
This guide is for freshers who are staring at a blank page and do not know where to start. You do not need a job history, a famous open-source profile, or an award-winning design. You need proof that you can build small frontend projects carefully.
Your first portfolio should answer a simple question: "Can this person be trusted with a junior frontend task?" The answer should come from the work itself, not from adjectives in the About section.
A beginner portfolio is not a personal brand campaign. It is a hiring artifact.
It should prove:
If your portfolio does that, it is already better than many beginner portfolios.
The easiest review path is:
If any step breaks, fix that before redesigning the site.
Keep the site simple.
Required sections:
| Section | What to include |
|---|---|
| Home | name, target role, one-line summary, links |
| Projects | three selected projects with live links and GitHub links |
| Skills | only tools you can explain |
| About | short learning story and work preference |
| Contact | email, GitHub, LinkedIn, resume |
Good homepage headline:
Frontend developer fresher building React, JavaScript, and responsive web projects.
Good supporting text:
I build small product-style interfaces with forms, API data, responsive layouts, and clear project notes.
Avoid:
Motivated developer creating digital solutions.
That tells the reader nothing.
Three finished projects are enough for the first version. Finished means deployed, documented, responsive enough to inspect on a phone, and honest about what is mocked.
| Project | Skill it proves | Why it helps |
|---|---|---|
| Multi-step form | forms, validation, state, accessibility | many junior tasks involve forms |
| API-backed search or dashboard | fetch, loading, empty, error, retry | proves you can work with data |
| Cart, booking flow, or expense tracker | user actions, derived state, persistence | proves interactive app logic |
Do not copy a tutorial exactly. If you use a tutorial for learning, change the requirements until the project becomes yours. Add one feature the tutorial did not include, change the data shape, and write down the decision you had to make.
Build a form that feels like a small product workflow.
Good ideas:
Required features:
Review details that matter:
Beginner version:
Improved version:
Project note:
What I built:A three-step application form with validation and review.Frontend decisions:I kept all form values in one state object so the review screen could read them easily. I validate each step before moving forward.What I learned:Form UX is not only inputs. Disabled states, error messages, and review screens matter.What I would improve:I would add server-side validation and better autosave.
Build something that uses data.
Good ideas:
Required features:
Review details that matter:
Beginner version:
Improved version:
Project note:
What I built:An API-backed product search page with filters and details.Frontend decisions:I separated the search input from the submitted query so the API is not called on every keypress.What I learned:The empty state and error state need different messages.What I would improve:I would add pagination and cache repeated searches.
Build something where user actions change state.
Good ideas:
Required features:
Review details that matter:
Beginner version:
Improved version:
Project note:
What I built:An expense tracker with categories, filters, and monthly totals.Frontend decisions:I calculate totals from the transaction list instead of storing totals separately.What I learned:Duplicate state can create bugs when values change in multiple places.What I would improve:I would add import/export and charts.
Each project page should have more than a screenshot.
Use this structure:
| Section | What to write |
|---|---|
| What it is | one paragraph explaining the project |
| Features | short bullets |
| Screens | key screenshots or GIF |
| Frontend decisions | state, API, layout, validation, or accessibility |
| What I learned | specific lessons |
| What I would improve | honest next step |
| Links | live demo and GitHub |
This helps interviewers see that you understand the work behind the final screen. It also gives you better interview answers because you are not trying to remember vague project details under pressure.
Clean GitHub is part of the portfolio. A reviewer may open the repo before the live demo, so do not treat GitHub as an afterthought.
For each repo:
.env.example if needed.README template:
# Project NameShort description.## Live demoLink## Features- Feature 1- Feature 2- Feature 3## Tech stackReact, TypeScript, CSS## Run locallynpm installnpm run dev## NotesOne tradeoff or limitation.
Your resume should point to the same proof.
Project bullets:
Avoid:
The resume gets attention. The portfolio earns the interview.
Make the order match the role. If the job asks for React, put the React project first. If it asks for UI developer skills, put the responsive page or form first. Do not make the reviewer hunt for the relevant proof.
If you feel stuck, follow this plan.
| Days | Work |
|---|---|
| 1-2 | Create portfolio shell and deploy it |
| 3-7 | Build multi-step form |
| 8-12 | Build API-backed search or dashboard |
| 13-16 | Build cart, booking flow, or expense tracker |
| 17 | Write READMEs |
| 18 | Write project pages |
| 19 | Fix mobile layout and broken links |
| 20 | Add resume and contact links |
| 21 | Apply to 10 relevant roles |
Your portfolio will not be perfect after 21 days. That is fine. A real, reviewable portfolio beats a perfect portfolio that never ships.
Before applying, do one clean-room check: open each project in an incognito window, click the main flow, resize to mobile width, and follow the README run command in a fresh folder. This catches the boring failures reviewers notice first.
After the first version:
The portfolio should improve through feedback, not endless redesign.
Avoid:
The best beginner portfolio is honest. It shows your current level and gives a team confidence that you can grow. If something is mocked, say it is mocked. If a feature is incomplete, name the next step instead of pretending it is done.
A frontend developer portfolio with no experience should make your learning visible. Build three useful projects, explain them clearly, clean up GitHub, and apply before perfection becomes another way to procrastinate.

A frontend developer roadmap in 2026 should start with the browser, then move through JavaScript, TypeScript, one major frontend framework, app architecture, accessibility, testing, performance, and interview practice. The right roadmap is not a list of every tool. It is an order of learning that keeps you employable without drowning you in optional technology.
Use this roadmap as a skills map. If you are starting from zero and need the broader beginner journey, read How to Become a Frontend Developer in 2026. This article is the detailed map of what to learn, what to skip for now, and what evidence each stage should produce.
| Stage | Learn | Build | You are ready to move on when |
|---|---|---|---|
| Web platform | HTML, CSS, browser behavior, DevTools | Static pages, forms, responsive layouts | You can explain layout, semantics, events, and network requests without a framework |
| JavaScript | Data structures, async code, DOM, modules | Search, filters, timers, API-backed widgets | You can debug state and async behavior from the console |
| TypeScript | Props, unions, generics, narrowing, API types | Typed forms, typed API responses, reusable components | You can remove unsafe any instead of hiding errors |
| Frontend framework | Components, state, lifecycle, composition, routing basics | Stateful UI flows, dashboards, product screens | You know where state belongs and how the framework updates the page |
| App architecture | Routing, data fetching, auth states, server/client boundaries | A multi-page product workflow | You can handle loading, empty, error, permission, and recovery states |
| Quality | Accessibility, testing, performance, security basics | Tested flows, keyboard-safe forms, measured pages | You can prove the UI works, not only that it renders |
| Interview readiness | JavaScript, framework concepts, CSS, APIs, system design | Timed exercises and explainable projects | You can solve, explain, test, and improve under time pressure |
Do not learn all rows at the same depth. A junior candidate needs broad competence and proof through projects. A senior candidate needs deeper tradeoff judgment, architecture, debugging, and mentoring evidence.
The core order has not changed: HTML, CSS, JavaScript, and the browser still come first. The emphasis has changed.
Framework choice matters, but it should come after the platform basics. React, Angular, Vue, and Svelte can all be valid choices depending on your target companies, local market, team stack, and learning style. React is common in many frontend roles, Angular is still common in enterprise teams, Vue is popular for approachable product development, and Svelte is worth considering when you like compiler-driven UI with less runtime code. Pick one main framework and get good enough to build complete flows.
TypeScript is also harder to treat as optional. Many modern frontend teams use it for framework apps, design systems, API contracts, and shared component libraries. For frontend learning, that means TypeScript is not a senior-only skill anymore.
Build tooling has become more practical. Vite, framework CLIs, and faster bundlers mean most learners do not need to hand-configure Webpack early. Learn what frameworks solve, but do not let a framework hide weak browser knowledge.
AI belongs in the roadmap too. It can explain errors, generate test cases, suggest refactors, and compare approaches. It should not replace reading docs, debugging in DevTools, writing code by hand, or reviewing accessibility behavior.
The browser is the runtime for every frontend framework. Weak browser knowledge shows up later as layout bugs, broken forms, poor accessibility, hydration mismatches, and confusing network behavior.
Learn HTML as page structure:
Learn CSS as layout and state:
Learn browser behavior:
Practice target:
| Project | What to prove |
|---|---|
| Responsive settings page | Layout, form controls, validation text, keyboard behavior |
| Pricing page with FAQ | Semantic structure, responsive CSS, disclosure state |
| API-backed profile card | Fetch, loading state, error state, retry behavior |
Frontend JavaScript is not only syntax. It is data changing over time while the user clicks, types, waits, navigates, and loses network access.
Prioritize:
async/await, timers, cancellation, and race conditionsBuild small exercises that reveal mistakes:
| Exercise | Mistake it catches |
|---|---|
| Debounced search | stale closures, repeated requests, missing empty state |
| Sortable table | mutation bugs, unstable sorting, weak rendering logic |
| Todo app with persistence | storage assumptions, serialization, state recovery |
| Polling status widget | timers, cleanup, network errors, duplicate updates |
Interview practice should begin here. Start with JavaScript interview questions, then add timed practice once the basics are steady.
TypeScript helps most when it models the messy edges of UI: optional API fields, unknown JSON, reusable component props, form values, and state transitions.
Learn:
typeof, in, discriminated unions, and custom guardsunknown over any when data comes from outside the appDo not begin with advanced type puzzles. A frontend developer gets more value from correctly typing API boundaries and component contracts than from writing clever utility types nobody wants to maintain.
Practice target:
| Build | TypeScript skill |
|---|---|
| Typed API client | response types, error types, unknown data |
| Reusable input component | props, event handlers, controlled values |
| Filter state model | unions, literals, derived state |
| Form result type | success/error states, discriminated unions |
Use TypeScript interview questions when you can explain the types in your own words. If you choose React, read TypeScript for React Developers for framework-specific practice.
A frontend framework helps you organize state, components, routing, forms, data loading, and shared UI. The important skill is deciding what changes, where it lives, and how the page should respond. React is a practical default for many learners, but it is not the only correct choice.
Pick based on your goal:
| Framework | Good choice when |
|---|---|
| React | Your target jobs mention React, Next.js, design systems, dashboards, or UI coding interviews |
| Angular | Your target jobs are enterprise teams with larger applications, strict conventions, and TypeScript-heavy codebases |
| Vue | You want an approachable framework with clear templates, component structure, and a strong product-app ecosystem |
| Svelte | You prefer compiler-driven UI, less boilerplate, and a smaller mental model for reactive components |
Whichever framework you choose, learn the same core ideas:
Learn:
For modern frameworks, add:
Do not make every project a framework project too early. A framework should clarify UI state, not compensate for weak HTML, CSS, or JavaScript.
If you choose React, practice with React interview questions, then build UI tasks such as Contact Form, Data Table, Tabs, and Image Carousel. If you choose Angular, Vue, or Svelte, build the same kinds of components in that framework: forms, tables, tabs, autocomplete, modal flows, dashboards, and data-backed product screens.
Many candidates can write components. Fewer can build a full product flow that behaves carefully under failure.
Learn:
Framework and meta-framework choice:
| Choice | When it makes sense |
|---|---|
| React with Vite | Learning React, building dashboards, practicing UI coding, smaller client-heavy apps |
| Next.js | React teams that need routing conventions, server-rendered pages, content-heavy apps, or auth-heavy products |
| Angular | Enterprise apps that benefit from built-in conventions, dependency injection, routing, forms, and TypeScript-first structure |
| Vue with Vite or Nuxt | Product apps where template clarity, component ergonomics, and progressive adoption matter |
| Svelte or SvelteKit | Smaller apps or teams that prefer compiler-driven reactivity and less runtime ceremony |
| Remix or React Router framework mode | React apps that lean heavily on routes, forms, data loading, and web-standard request handling |
Pick one main framework after the browser and JavaScript basics. Learn enough of the others to read job descriptions, not enough to split your attention across three stacks.
Accessibility is not a separate phase you bolt on before launch. It affects the elements you choose, the state you expose, the keyboard behavior you support, and the way errors are announced.
Learn:
Project checks:
Use accessibility practice inside every project. A keyboard-broken form is not job-ready UI.
Testing is easier to learn when the goal is clear: protect important behavior from regressions.
Learn:
Good first tests:
| Feature | Useful test |
|---|---|
| Form | Shows validation errors, disables submit while pending, recovers after API failure |
| Data table | Applies filters, preserves sorting, handles empty results |
| Auth-gated page | Redirects unauthenticated users and preserves destination |
| Upload flow | Shows progress, handles cancellation, displays retry |
Testing should not wait until a project is finished. Add tests when behavior becomes easy to break.
Frontend performance in 2026 is not only bundle size. It includes loading, rendering, images, fonts, third-party scripts, data waterfalls, server response time, and main-thread work.
Learn:
Performance practice:
Do not start with advanced micro-optimizations. A missing image size, a client-only marketing page, or a slow API waterfall usually matters more than a premature useMemo.
Tools should reduce friction. They are not the roadmap.
| Tool area | Learn first | Learn later |
|---|---|---|
| Editor | VS Code or your preferred editor, debugger, TypeScript errors | custom editor automation |
| Package manager | npm or pnpm basics, scripts, lockfiles | workspace tuning |
| Build tool | Vite or framework CLI | custom bundler configuration |
| Version control | Git branches, commits, pull requests, conflict resolution | advanced rewriting workflows |
| Styling | CSS modules, Tailwind, or the team's system | design token pipelines |
| Data fetching | fetch, framework loaders/actions, TanStack Query basics | custom cache layers |
| Testing | Vitest/Jest, Testing Library, Playwright | visual regression infrastructure |
| Deployment | Vercel, Netlify, Cloudflare, or company CI basics | multi-region rollout strategy |
The best tool choice is the one that lets you build and debug more product behavior. If a tool takes a week to configure before you understand the problem it solves, postpone it.
A roadmap needs proof. Courses and notes are not enough.
| Stage | Project | Requirements |
|---|---|---|
| Platform | Accessible form flow | labels, validation, keyboard behavior, responsive layout |
| JavaScript | Searchable data table | fetch, sorting, filtering, pagination, empty state |
| TypeScript | API-backed dashboard | typed response, error model, reusable chart/list components |
| Framework | Product settings app | tabs, forms, optimistic save, dirty-state warning |
| App architecture | Mini SaaS workflow | auth states, routing, permissions, billing-like flow, tests |
| Quality | Performance and accessibility pass | measured before/after notes, keyboard audit, critical tests |
| Interview | Timed UI challenges | explainable solution, edge cases, cleanup, follow-up improvements |
Each finished project should include a short engineering note:
That note matters. It turns a demo into hiring evidence.
The roadmap changes by target level.
| Target | Spend more time on | Spend less time on |
|---|---|---|
| Beginner | HTML, CSS, JavaScript, one framework, portfolio projects | framework debates, advanced state libraries, microfrontends |
| Internship or junior | forms, API integration, debugging, TypeScript basics, GFE practice | complex architecture diagrams |
| Mid-level | feature ownership, state modeling, tests, accessibility, performance | copying tutorials |
| Senior | tradeoffs, system design, migrations, cross-team contracts, production debugging | isolated toy apps |
| Specialist | one depth area such as design systems, frontend infrastructure, accessibility, or performance | trying to specialize before shipping product UI |
For senior growth, pair this roadmap with Senior Frontend Developer Skills. For title progression and scope, use Frontend Developer Career Path.
Interview preparation should track the same skill order, but with tighter feedback loops.
| Area | Practice |
|---|---|
| JavaScript | arrays, objects, promises, closures, timers, event loop, DOM manipulation |
| CSS | layout, responsive behavior, specificity, positioning, accessible states |
| Framework | state, lifecycle, forms, rendering, component design |
| APIs | REST, status codes, pagination, caching, retries, error states |
| TypeScript | component props, unions, generics, narrowing, API data |
| UI coding | forms, tables, autocomplete, tabs, carousel, file explorer |
| System design | data flow, component boundaries, performance, accessibility, failure modes |
Start with quiz questions for fast feedback. Use user interface coding questions when you need implementation practice. Add front end system design questions once you can build product flows without getting stuck on basic component state.
The most common mistake is learning tools in the order they look exciting instead of the order they remove real bottlenecks.
Avoid these traps:
The fix is simple but not easy: build smaller complete flows, test the uncomfortable states, and explain the tradeoffs.
This timeline assumes consistent part-time study. Move faster if you already program. Move slower if the projects feel shallow.
| Timeframe | Main goal | Output |
|---|---|---|
| Weeks 1-4 | Browser, HTML, CSS, JavaScript basics | responsive form and API widget |
| Weeks 5-8 | JavaScript depth and DOM behavior | searchable table, debounced search, persisted state |
| Weeks 9-12 | TypeScript and framework basics | typed components and form flow |
| Months 4-5 | App architecture | multi-page app with routing, auth states, API data, and error handling |
| Month 6 | Quality pass | tests, accessibility fixes, performance notes, deployed portfolio |
| Months 7-12 | Interview and depth | GFE practice, system design, stronger projects, specialist exploration |
The calendar is only useful if the outputs are real. A shallow six-month checklist is weaker than three carefully built projects that show product judgment.
A good frontend developer roadmap in 2026 is selective. Learn the platform, add JavaScript depth, use TypeScript to model risk, choose one frontend framework, build full product flows, and prove quality through accessibility, tests, and performance work.
The goal is not to know every frontend tool. The goal is to become the person a team can trust with user-facing behavior.

In India, a typical frontend developer salary in 2026 sits around Rs 6.4-7.5 LPA in broad self-reported datasets, but product companies, GCCs, and senior roles can pay much higher. Treat averages as a starting point, not your ceiling.
Salary data is messy because every site measures a different slice of the market. Some report base pay, some total pay, some job listings, and some self-reported profiles.
| Source | Latest accessible data | What it says | Caveat |
|---|---|---|---|
| Glassdoor India | Updated May 9, 2026, 4.1K salary submissions | Median total pay around Rs 6.4 LPA, with a reported range around Rs 4.49-10.2 LPA and 90th percentile around Rs 18.67 LPA | Self-reported and title-dependent |
| PayScale India | Updated May 14, 2026, 927 profiles | Average base salary Rs 6.57 LPA, base range around Rs 2.91-20 LPA | Base salary focus; sample skews by profile submissions |
| Indeed India | Updated May 8, 2026, 205 salary reports | Average base salary around Rs 6.86 LPA, with higher city and company examples | Smaller sample and listing/reporting mix |
| NodeFlair India | Updated June 8, 2026 | Median base salary Rs 62,500 per month, or about Rs 7.5 LPA; range Rs 37,500-1,87,500 per month | Mixes verified salaries and curated job listings |
| Adecco India Salary Guide 2026 | 2026 guide | Front-end developer bands from about Rs 5-10 LPA at 0-3 years to about Rs 40-73 LPA at 15+ years | Recruiter/employer guide, not a self-reported salary dataset |
| AmbitionBox | Latest accessible frontend software developer result was updated in 2025 | Historical context showed roughly Rs 2-16 LPA for less than 1 year to 4 years | Treat as 2025 context unless the page refreshes with 2026 data |
For early-career roles, Rs 6-8 LPA is a reasonable broad-market midpoint. Strong product companies, GCCs, funded startups, and senior specialist roles can move much higher.
The sources are useful, but none of them should be treated as a perfect salary truth.
Glassdoor and PayScale are good broad-market anchors because they have salary-profile samples and publish clear ranges. They are weaker for top-of-market product roles because titles and seniority can be inconsistent.
Indeed is useful for live market signals because it connects salaries, job postings, cities, and companies. Its current average is based on a smaller sample than Glassdoor, so use it to compare patterns rather than as the final number.
NodeFlair is useful because it presents monthly base salary and current job-listing context. The caveat is that recently submitted salaries may lag behind the page update date, so the salary range should be treated as a directional benchmark.
Adecco is useful as an employer-side salary guide. It is especially helpful for experience bands, but it is not a self-reported employee salary database.
AmbitionBox is useful for India-specific company and title context. For this article, the latest accessible frontend software developer result is still 2025, so it should support historical context only, not the headline 2026 number.
Glassdoor, PayScale, Indeed, NodeFlair, Adecco, and AmbitionBox are not measuring the same thing.
The biggest differences are:
Two developers with the same title can see very different numbers. A frontend developer building marketing pages at a services firm and a frontend engineer owning a high-traffic product surface at a GCC are both "frontend developers" in salary databases. They are not the same market profile.
Use these bands as a practical reading of the 2026 market, not as guaranteed offers.
| Experience | Broad-market expectation | Product company or GCC upside | What usually changes pay |
|---|---|---|---|
| 0-2 years | Rs 3-7 LPA | Rs 5-10 LPA | Web foundations, React basics, TypeScript, portfolio quality, internships |
| 2-5 years | Rs 6-14 LPA | Rs 10-22 LPA | Owning features, API integration, testing, performance awareness |
| 5-8 years | Rs 12-24 LPA | Rs 18-40 LPA | UI architecture, design systems, accessibility, mentoring, delivery judgment |
| 8-12 years | Rs 20-35 LPA | Rs 32-60 LPA | Leading frontend scope, cross-team decisions, performance and reliability ownership |
| 12+ years | Rs 30-50+ LPA | Rs 45-75+ LPA | Staff, principal, lead, architect, or manager scope; company type matters heavily |
The jump from mid-level to senior is where frontend pay starts to diverge. Years alone do not create the jump. Scope does.
Employer type often matters more than the title.
| Employer type | Typical pattern |
|---|---|
| IT services firms | More structured bands, slower compensation growth, title inflation possible |
| Indian product startups | Higher upside when the company is funded and frontend is core to the product |
| GCCs and multinational product teams | Stronger pay for engineers who meet a higher interview bar |
| Agencies | Wide range; depends on client quality and technical depth |
| Early-stage startups | Cash may be lower or uneven, but scope can be high |
| Large consumer internet companies | Strong pay for complex UI, performance, and product ownership |
If you are comparing two offers, do not stop at CTC. Ask what the frontend team owns. A lower-looking offer can be better if the work builds stronger experience, but only if compensation, mentorship, and company quality are still reasonable.
Use How to Evaluate Companies as a Front End Engineer before accepting a role.
Indeed's 2026 India salary page surfaced higher average salaries in Hyderabad, Gurgaon, Bengaluru, Pune, and Ahmedabad. Its current city examples include Hyderabad around Rs 11.12 LPA, Gurgaon around Rs 8.55 LPA, Bengaluru around Rs 7.96 LPA, Pune around Rs 7.92 LPA, and Ahmedabad around Rs 7.40 LPA. Treat city data carefully because sample sizes can be small, and one or two high-paying employers can move the average.
In practice:
Location helps, but it does not replace skill and company selection.
One common mistake in India salary research is mixing base salary, CTC, total pay, bonus, stock, and monthly take-home as if they were the same thing.
When reading an offer, separate:
A Rs 18 LPA CTC offer with a high variable component can be weaker than a Rs 15 LPA offer with cleaner fixed pay. A startup ESOP component can be meaningful, but only if you understand vesting, strike price, liquidity, and whether the company has a realistic path to an exit.
For negotiation, ask for the compensation breakup before comparing offers. Averages from salary sites are useful only after you know what number you are comparing against.
The highest-paid frontend engineers are rarely paid only for React syntax. They are paid because they reduce product and engineering risk.
Skills that move compensation:
If your CSS is weak, fix it. The top CSS mistakes made by front-end engineers are still common in paid work.
To build interview evidence for higher-paying frontend roles, practice TypeScript interview questions, React interview questions, UI coding questions, and system design questions. These are closer to the signals product companies and GCCs usually test than generic portfolio pages.
Do not walk into negotiation with one average number. Use a range and explain your fit.
Better negotiation evidence includes:
For example, "Glassdoor and PayScale put the broad market around Rs 6.4-6.6 LPA, but this role is a TypeScript-heavy product role with design system ownership. Based on the scope and my experience, I am targeting X" is stronger than quoting a single website average.
Frontend developer salary in India in 2026 is not one number. Broad datasets cluster around Rs 6.4-7.5 LPA, but roles at stronger frontend teams can move far above that when the engineer owns product quality, performance, accessibility, TypeScript, and cross-team UI architecture.
Use salary sites to anchor the conversation. Use skill depth and company selection to change the conversation.

The frontend developer career path moves from completing scoped tasks to owning product outcomes. In 2026, progression is less about years and more about scope, judgment, verification, and impact.
Titles vary by company, but the pattern is similar: junior, mid-level, senior, staff or lead, and sometimes manager.
| Level | Typical scope | What the role proves |
|---|---|---|
| Learner | Practice projects and foundations | You can build basic UI and explain your code |
| Junior frontend developer | Scoped tasks inside an existing codebase | You can follow patterns and ask good questions |
| Mid-level frontend developer | Features with moderate ambiguity | You can own delivery with limited guidance |
| Senior frontend developer | Ambiguous product work and technical decisions | You can reduce risk and guide others |
| Staff or lead frontend engineer | Cross-team frontend direction | You can multiply the work of several engineers |
| Engineering manager | People, delivery, and team health | You can build the environment where engineers do good work |
The ladder is not universal. Startups blur levels. Big companies define them more formally. Some engineers stay technical. Some move into management. Some specialize deeply.
The learner stage is about becoming hireable. You need web foundations, a framework, and enough product sense to build useful projects.
A junior frontend developer is expected to:
To move from learner to junior, prove that you can finish small work reliably. Your portfolio should show forms, API usage, responsive layout, loading states, and error states. A pile of cloned landing pages is weaker than one product workflow that behaves carefully.
Use How to Become a Frontend Developer in 2026 if you need the learning sequence.
The mid-level jump is about independence. A mid-level frontend developer can take a feature, clarify requirements, make reasonable technical choices, and deliver without needing constant correction.
At this stage, you should become solid at:
The signal is reliability. Your team should trust you with feature work that has some unknowns.
To reach mid-level, stop waiting for perfect tickets. Learn to ask the questions that make the work clear:
For this stage, practice JavaScript questions, React questions, and focused UI tasks such as Contact Form, Data Table, and Auth Code Input.
The senior jump is about judgment. A senior frontend developer does more than finish bigger tickets. They prevent bad decisions from becoming expensive.
Senior frontend engineers are trusted with:
They also know when not to add complexity. Seniority is not the number of abstractions you create. It is the quality of your tradeoffs.
In the AI era, this level matters more. Generated code can create a lot of output quickly, but senior engineers verify whether the output is correct, accessible, maintainable, and aligned with the product.
At this point, add TypeScript questions, front end system design questions, and larger UI problems such as File Explorer.
Read Senior Frontend Developer Skills: What You Need to Land the Role in 2026 for the deeper skill map.
Promotion is easier when you collect evidence before the conversation starts. Do not rely on "I have been here for two years" as your main case.
| Target level | Evidence that helps |
|---|---|
| Junior to mid-level | Features shipped with less supervision, fewer repeated review comments, cleaner state handling, and better debugging notes |
| Mid-level to senior | Ambiguous work clarified, technical risks named early, components or flows improved for other engineers, and quality issues prevented |
| Senior to staff or lead | Cross-team problems solved, migrations guided, standards adopted, measurable performance or reliability improvements, and other engineers made more effective |
| Engineer to manager | Hiring support, mentoring, planning, feedback, team health, and delivery improvements beyond personal coding output |
Write this evidence down as it happens. Promotion packets are much easier when you have concrete examples instead of trying to reconstruct a year of work from memory.
Staff and lead frontend roles are about broader influence. You are no longer measured only by your own delivery. You are measured by whether teams make better technical decisions because you are involved.
Typical work includes:
Staff engineers do not need to be the loudest people in the room. They need to notice important problems, frame them clearly, and help teams make progress.
Lead titles vary. In some companies, "lead" means technical leadership. In others, it includes people management. Clarify that before accepting the role.
Frontend developers can also move into engineering management. Management is a different job, not a promotion that simply means "more senior engineer."
Engineering managers work on:
Good managers need technical context, but they are not judged mainly by their code. They are judged by whether the team can do good work consistently.
If you love the technical depth of frontend, you do not have to become a manager. A senior, staff, or principal frontend path can remain technical.
Frontend has several specialist paths. These can exist at mid-level, senior, or staff scope depending on the company.
| Track | What you work on |
|---|---|
| Product frontend engineer | Complex product flows, UX behavior, and feature delivery |
| Design systems engineer | Shared components, tokens, accessibility, documentation, and adoption |
| Frontend platform engineer | Build tooling, monorepos, CI, testing infrastructure, and developer experience |
| Web performance engineer | Metrics, rendering, loading, bundle cost, and runtime behavior |
| Accessibility specialist | Usability across assistive technology, keyboard behavior, semantics, and audits |
| Frontend-heavy fullstack engineer | UI plus API and backend changes for feature ownership |
| Web platform specialist | Browser APIs, offline behavior, media, graphics, WebAssembly, or advanced runtime work |
Specializing too early can narrow your options. Build product frontend competence first, then choose depth.
Career paths are cleaner on paper than inside companies.
At a startup, a "frontend developer" may own product UI, backend routes, analytics events, customer bugs, and deployment fixes in the same week. You might gain senior scope before you have a senior title.
At a large company, the title may be slower, but the expectations are clearer. You may need promotion evidence, peer feedback, technical design examples, and cross-team impact.
Neither model is automatically better. The key is knowing what evidence you are building.
The fastest career growth usually comes from work that increases trust.
Useful habits:
For company selection, use How to Evaluate Companies as a Front End Engineer. The company you choose can accelerate or slow your path.
The frontend developer career path in 2026 is not "junior writes components, senior writes more components." It moves from task completion to product and technical ownership.
Your title will vary by company. Your real growth shows in the size of the problems people trust you to handle, the quality of your decisions, and the number of people whose work gets better because of yours.

A senior frontend developer is not measured by component speed alone. In 2026, seniority means better judgment: you can own ambiguous UI work, verify AI-assisted code, prevent regressions, and make product interfaces reliable.
The bar has moved. Code generation is cheaper. Correctness, taste, tradeoffs, and ownership matter more.
A junior developer is usually trusted with well-scoped tasks. A mid-level developer can own features with some guidance. A senior frontend developer can take unclear product goals, break them into technical work, identify risks, coordinate with other functions, and ship something the team can maintain.
That does not mean seniors stop coding. It means their code sits inside a larger responsibility.
Senior frontend engineers are expected to answer questions like:
| Area | Mid-level habit | Senior signal |
|---|---|---|
| Component work | Builds components from designs | Designs component APIs that are hard to misuse |
| State | Makes the current feature work | Chooses state boundaries that survive future changes |
| CSS | Fixes layout bugs | Prevents layout classes, overflow, and responsive bugs through better structure |
| Accessibility | Runs a checklist near the end | Builds keyboard, semantics, labels, focus, and contrast into the design of the UI |
| Performance | Reacts when the app feels slow | Measures cost and removes waste before it becomes user pain |
| Testing | Adds tests when requested | Protects critical flows with the right level of tests |
| APIs | Consumes endpoints | Negotiates contracts, loading states, failure states, and data shape changes |
| AI tools | Accepts useful output | Reviews generated code like a risky pull request |
| Leadership | Helps when asked | Creates clarity for other engineers without taking over everything |
Senior frontend developers understand that the browser is the runtime. React does not replace HTML, CSS, layout, rendering, networking, and accessibility.
You should be comfortable with:
Many frontend incidents are not framework problems. They are browser problems wearing framework clothing.
A senior frontend engineer designs components that other people can use safely.
Good component design includes:
A clever abstraction is not the aim. The aim is to reduce repeated decisions and prevent repeated bugs.
Senior frontend developers use TypeScript to model risk, not to decorate JavaScript.
You should know how to:
Use TypeScript interview questions for senior frontend developers as a calibration point.
Accessibility is not a bonus skill for senior frontend roles. It is part of building usable software.
Senior engineers catch issues such as:
AI-generated markup can look fine visually while failing semantic and keyboard behavior.
Senior frontend developers do not guess about performance for long. They measure.
Useful areas include:
Performance is product quality. Users do not care whether the slowness came from JavaScript, a large image, hydration, or an API. They only experience a slow product.
Senior engineers know that not every bug needs the same test. They choose the test based on risk.
Typical coverage choices:
The senior skill is knowing what must not break and putting protection there.
Frontend engineers do not need to become backend specialists, but senior frontend developers should understand the API boundary well.
You should be able to discuss:
REST knowledge matters because frontend decisions often depend on API contracts. Review REST API interview questions for frontend developers if you want to test that boundary.
In 2026, a senior frontend developer must know how to work with AI tools without lowering the team's quality bar.
AI usage is already common. Stack Overflow's 2025 Developer Survey reported broad AI-tool usage and also found that 66% of respondents were frustrated by AI solutions that were "almost right." DORA's 2025 AI-assisted software development report described AI as an amplifier of an organization's existing strengths and weaknesses.
For senior frontend work, that means AI helps more when the engineer already knows what good UI, safe state, accessible markup, and maintainable component design look like. If the engineer cannot review the output, AI can hide risk instead of removing it.
When reviewing generated frontend code, ask:
The senior skill is not refusing AI. It is making sure the team remains responsible for what ships.
Senior frontend developers create clarity. They do not need a staff title to do that.
Useful senior behaviors include:
Many mid-level developers get stuck here. They can finish their own work, but they do not yet improve the work around them.
Build evidence, not a skill list.
For your next few projects or work items, capture:
Use GreatFrontEnd's TypeScript interview questions, React interview questions, UI coding questions, and front end system design questions to pressure-test senior readiness. Good senior practice problems include Data Table, File Explorer, and Autocomplete.
Those stories are stronger in interviews than saying you know React, TypeScript, and testing.
Senior frontend interviews often test the gaps between coding skill and ownership.
Expect questions such as:
Useful answers are specific. Name the constraints, name the risk, make a tradeoff, and explain how you would verify the result.
Senior frontend developer skills in 2026 are about judgment under product constraints. You still need HTML, CSS, JavaScript, TypeScript, React, accessibility, performance, and testing. But the senior signal is how you use them to reduce risk and increase team output.
Senior work is less about writing more code and more about making the right frontend work happen.

To become a frontend developer in 2026, learn the web fundamentals first, then build apps with JavaScript, TypeScript, and React, then prove you can ship accessible, fast, tested UI. Do not start by collecting libraries.
A realistic path takes months, not a weekend. You are trying to become useful on a product team, not collect every tool.
You can become a frontend developer with different frameworks, but JavaScript, TypeScript, and React are still practical default choices for most learners.
GitHub's 2025 Octoverse report said TypeScript overtook both Python and JavaScript in August 2025 to become the most used language on GitHub, and noted that major frontend frameworks now scaffold TypeScript by default. JetBrains' 2025 developer ecosystem report also called TypeScript the language with the most dramatic rise in usage over the previous five years.
React remains a common hiring signal too. InfoQ's summary of the State of JavaScript 2025 survey reported React as the most used frontend framework among respondents, with Next.js also widely used. That does not mean React is the only good framework. It means React and TypeScript are efficient bets for interview preparation and portfolio work.
Start with HTML, CSS, JavaScript, and the browser. These are not beginner-only topics. Senior frontend engineers still debug problems at this layer.
Learn HTML as structure, not decoration:
Learn CSS as a layout system:
Then learn JavaScript deeply enough to build interactive pages:
Do not skip forms. A lot of frontend work is still forms: validation, disabled states, keyboard behavior, error messages, async submission, and recovery after failure.
Before React, build a few small projects with plain HTML, CSS, and JavaScript:
These projects show you what frameworks are solving. If you skip this stage, React can become a place to hide weak web knowledge.
Use browser DevTools early. Inspect layout, network requests, console errors, performance traces, storage, and accessibility hints.
React remains a common hiring signal, and TypeScript is now expected in many frontend teams with a real interview bar. Learn them together once your JavaScript is steady.
For React, learn:
For TypeScript, learn:
any as a habitYou do not need to memorize every React API. You do need to understand how UI changes over time and how data moves through your components.
A frontend developer builds applications, not isolated components. This stage connects your UI to product behavior.
Spend time with:
Learn REST APIs well enough to work with backend engineers. You should understand status codes, headers, JSON, caching, idempotency, pagination, rate limits, and authentication. The REST API interview questions for frontend developers are useful even before interviews because they expose common gaps.
Many candidates separate themselves here.
Accessibility means the interface works with keyboard navigation, screen readers, visible focus states, labels, semantic HTML, color contrast, and predictable behavior.
Performance means you can measure and reduce the cost of JavaScript, images, fonts, rendering, layout shifts, slow API calls, and unnecessary re-renders.
Testing means you can protect important behavior. Learn unit tests for logic, component tests for UI behavior, and end-to-end tests for critical flows.
Security basics matter too. Frontend engineers should understand cross-site scripting, unsafe HTML, token storage tradeoffs, permissions, CSRF at a high level, dependency risk, and privacy-sensitive data.
You do not need to be an expert in every area. You do need to know enough to avoid shipping careless UI.
A portfolio should prove that you can make product decisions instead of only copying designs.
Build three projects:
| Project | What it should prove |
|---|---|
| A dashboard | Data fetching, tables, filters, charts, loading states, empty states, and responsive layout |
| A form-heavy app | Validation, accessibility, error recovery, async submission, and state management |
| A product workflow | Routing, authentication states, permissions, API integration, and testing |
For each project, write a short case note:
Hiring teams do not need more cloned landing pages. They need evidence that you can think.
Use AI tools to explain unfamiliar code, generate first drafts, write test cases, and compare approaches. Then verify the output yourself.
The mistake is using AI to skip the learning step. If you ask AI to build every component before you understand HTML, CSS, JavaScript, and state, you may finish projects faster but become weaker in interviews and code reviews.
Use AI as a practice partner:
Do not use AI as a replacement for reading docs, using DevTools, or debugging your own mistakes.
For frontend work, check:
AI speeds up drafts. It can also speed up mistakes. Your value is knowing the difference.
AI changes the entry-level bar. Employers do not need a junior developer only to produce a first draft of a component. They need someone who can work with drafts, requirements, feedback, and bugs without lowering the team's quality.
A beginner should build evidence for:
| Skill | What it looks like in 2026 |
|---|---|
| Product behavior | You handle loading, empty, error, disabled, permission, and mobile states |
| Web foundations | You can explain the HTML, CSS, JavaScript, and browser behavior behind your UI |
| AI verification | You can review generated code instead of accepting it blindly |
| Debugging | You can use DevTools, logs, network panels, and TypeScript errors to find problems |
| Accessibility | You think about keyboard behavior, labels, focus, semantics, and contrast early |
| Communication | You can explain tradeoffs in plain language during reviews and interviews |
The roadmap starts with the platform and then adds React, TypeScript, projects, testing, and AI-assisted workflows. The order is intentional.
Frontend interviews usually test a mix of JavaScript, React, CSS, browser behavior, API knowledge, and product debugging.
Practice these areas:
Use GreatFrontEnd's JavaScript interview questions, React interview questions, quiz questions, and user interface coding questions to turn the roadmap into practice. For project-style drills, start with Contact Form, Data Table, and Image Carousel.
If you are targeting senior roles later, start building depth with TypeScript interview questions for senior frontend developers.
You are not job-ready because you watched a React course. You are closer to job-ready when you can take a messy requirement and turn it into working UI without someone else rescuing the details.
Before applying seriously, check whether you can:
If you cannot do these yet, keep building. If you can do most of them, start applying while improving the gaps. Waiting until you feel perfectly ready usually means waiting too long.
After you can build and ship product UI, choose one or two specialist tracks:
Do not begin here. Expert tracks are useful after you have product experience.
Do not read this as "six months guarantees a job." Read it as a readiness window.
If you already have some programming experience and can study consistently, 6 months can be enough to start applying for internships or junior frontend roles. If you are starting from zero, learning part-time, or switching careers while working, 9-12 months is more realistic.
| Phase | Timeframe | What you should be able to do |
|---|---|---|
| Web foundations | Months 1-2 | Build responsive pages, handle forms, write JavaScript interactions, use DevTools, and fetch data from APIs |
| Application basics | Months 3-4 | Build React apps with TypeScript, routing, forms, state, API integration, loading states, and error states |
| Job-ready practice | Months 5-6 | Finish portfolio projects, deploy them, practice GFE questions, explain tradeoffs, and start applying selectively |
| Interview depth | Months 7-12 | Improve weak projects, do more interviews, practice system design, add testing and accessibility depth, and study specialist topics only after the basics are stable |
The main milestone is not the calendar. It is whether you can build a working product flow, explain your decisions, debug mistakes, and pass common frontend interview exercises.
Do not try to become a frontend developer by memorizing a stack. Learn the platform, build interfaces that survive messy states, add React and TypeScript with purpose, and prove your judgment through projects.
The frontend market in 2026 rewards people who can ship usable product UI and explain their decisions. Build toward that.

Yes, frontend development is still a good career in 2026 if you can build product UI that holds up when data, state, accessibility, performance, edge cases, and AI-assisted code all meet in the same feature.
That distinction matters because many beginners are asking the wrong version of the question.
Frontend used to be seen as the easiest software path to enter. Learn HTML, CSS, JavaScript, React, build a portfolio, apply widely. That path still exists, but it is more crowded and less forgiving.
Three things changed:
Frontend is not dying, but shallow frontend work is easier to replace. A person who can only assemble prompted components has a weaker market position than someone who can verify behavior, debug product issues, and make tradeoffs.
For the broader "dying" question, read Is Frontend Development Dying in 2026?.
AI changes frontend development by making first drafts cheaper. It can generate a React component, write CSS, suggest tests, explain an error, convert JavaScript to TypeScript, or produce a quick API integration.
Useful, yes, but it also changes the hiring signal.
The old signal was often: can you build the screen? The 2026 signal is closer to: can you decide whether the generated screen is correct, accessible, maintainable, and aligned with the product?
Stack Overflow's 2025 Developer Survey found that 84% of respondents were using or planning to use AI tools, while more developers actively distrusted AI accuracy than trusted it. DORA's 2025 AI-assisted software development report frames AI as an amplifier of existing strengths and weaknesses, not as a replacement for sound engineering practice.
For frontend developers, that means AI can help you move faster if you already understand the web. If you do not, it can hide mistakes behind code that looks plausible.
AI is often weak at:
Those are exactly the areas where good frontend engineers still matter.
Frontend hiring is shifting from output volume to verification and ownership.
| Earlier expectation | 2026 expectation |
|---|---|
| Build screens from a design | Build product flows that handle real data, errors, loading, permissions, and accessibility |
| Know one framework | Understand the browser, JavaScript, TypeScript, CSS, APIs, and the framework |
| Use component libraries quickly | Know when a component library helps and when custom behavior needs careful implementation |
| Ship the happy path | Test edge cases, keyboard behavior, responsive states, and API failures |
| Ask AI for code | Review AI output for correctness, security, accessibility, and maintainability |
| Show a portfolio | Explain tradeoffs, debugging decisions, and how the project would behave in production |
AI makes frontend harder for people who rely on drafts and better for candidates who can review, debug, and explain their work. If a draft takes seconds, the valuable skill is deciding what should ship.
The software market still has demand, but it is uneven. In the US, the Bureau of Labor Statistics projects 15% growth for software developers from 2024 to 2034, much faster than the average for all occupations.
India's hiring picture is more selective. Naukri's March 2026 Jobspeak report showed white-collar hiring growth, but IT was flat while AI/ML hiring grew much faster.
The broader global picture points the same way. The World Economic Forum's Future of Jobs Report 2025 still lists software and applications developers among roles expected to grow through 2030.
Frontend jobs are not easy to get by default. Software work is not disappearing, but the hiring bar has shifted. A resume that lists React and a few projects is weaker than evidence that you can build and reason through product UI under constraints.
Every serious digital product needs user-facing software. Banking apps, SaaS dashboards, developer tools, marketplaces, internal tools, healthcare portals, education platforms, commerce sites, and AI products all need interfaces that people can understand and trust.
Frontend engineers sit at a difficult boundary. They translate product intent, design systems, backend APIs, user behavior, browser constraints, accessibility needs, and performance budgets into working software.
Most useful frontend work happens at that boundary.
The work that still earns trust includes:
Frontend work here is product engineering in the browser: user flows, constraints, failure states, and the details people notice when software breaks.
Frontend is a weaker career bet if you plan to stop at surface-level skills.
The risky profile looks like this:
This profile is more vulnerable in 2026 because AI tools can produce similar output quickly. Companies do not need to hire a full-time engineer for code that still requires heavy review by someone else.
Frontend candidates therefore need to show judgment. AI can draft a component. It will not reliably know whether the flow is accessible, the form state is recoverable, the API error is handled, or the product behavior is right.
Frontend work with staying power combines web foundations with product judgment.
You do not need to master everything before your first job, but you do need to build toward these areas:
| Area | Why it matters |
|---|---|
| HTML and accessibility | Users need interfaces that work beyond mouse clicks and perfect eyesight |
| CSS layout | Most UI bugs are layout, spacing, overflow, or responsive behavior problems |
| JavaScript and TypeScript | Frontend apps are stateful software, not static pages |
| React or another framework | Teams need maintainable UI architecture |
| APIs and data fetching | Product UI depends on network and backend behavior |
| Testing | Teams need confidence when features change |
| Performance | Slow UI loses trust, revenue, and user patience |
| Product thinking | Good frontend work solves user problems instead of only finishing design tickets |
| AI verification | Generated code still needs a human who knows what correct means |
If you want a staged learning path, use How to Become a Frontend Developer in 2026 as your roadmap.
If you want to test whether your skills are beyond surface-level UI, work through JavaScript interview questions, React interview questions, and user interface coding questions.
A useful first frontend role is not always the highest-paying one. It gives you repeated practice with product UI under review.
Look for:
Be cautious with roles where frontend means only slicing static pages, editing templates, or wiring prebuilt components with no product ownership. That experience can be useful at the beginning, but it can trap you if it never grows.
Frontend is not a single-track career. After the first few years, you can move toward different kinds of depth.
Common growth paths include:
That variety keeps the career interesting. You can start with visible product UI, then choose the kind of complexity you want to become known for.
Frontend is a good career fit if you enjoy the user-facing side of software. You should like details, but not only visual details. The work also needs patience with state, data, edge cases, and browser behavior.
You may enjoy frontend if you:
Frontend is also a good base for product engineering. Many strong product engineers start with frontend and add backend fluency over time.
Do not choose frontend only because it looks easier than backend. The beginner path may feel friendlier, but professional frontend work still demands careful engineering.
You may prefer backend, data, infrastructure, security, or mobile if you dislike:
Choosing the wrong path because it looks easy is expensive. Choose the problems you are willing to keep solving.
Frontend development is a good career in 2026 if you treat user-facing software as engineering work. The market is less generous to shallow skills, and AI has made basic code cheaper.
That should not push you away from frontend. It should push you to learn it properly. Build interfaces that work under pressure, explain your decisions, test the behavior, and understand the product. That version of frontend still has room.

Frontend wins if you want visible product ownership and enjoy browser/UI complexity. Backend wins if you want deeper ownership of systems, data, security, reliability, and business logic. Neither path wins for everyone.
The right question is not "Which career is better?" It is "Which kind of hard work do I want to get good at?"
Frontend developers build the part of a product users touch. That includes pages, flows, forms, dashboards, editors, navigation, state transitions, errors, loading states, accessibility, and performance in the browser.
At junior levels, this may look like building components from designs. At senior levels, it becomes product engineering: deciding how the UI should behave, how data should move through the app, how to prevent regressions, and how to make the experience fast and usable for many kinds of users.
Good frontend work often requires:
Frontend is a good fit if you like visible feedback. When the work is right, users can feel it immediately. When it is wrong, they can feel that too.
Backend developers build the systems behind the product. That includes APIs, databases, queues, permissions, authentication, business rules, integrations, search, payments, logging, reliability, and infrastructure-facing code.
At junior levels, backend work may start with routes, CRUD APIs, and database queries. At senior levels, it becomes systems ownership: data modeling, scaling paths, failure handling, security boundaries, observability, and tradeoffs that affect many teams.
Good backend work often requires:
Backend is a good fit if you like invisible correctness. Good backend work may be noticed only because the product keeps working.
Software remains a growing field, but the entry bar is higher than it was during the hiring boom. The US Bureau of Labor Statistics projects 15% growth for software developers from 2024 to 2034, much faster than the average for all occupations. For web developers and digital designers, it projects 7% growth from 2024 to 2034.
India's market is more uneven. Naukri's March 2026 Jobspeak report showed white-collar hiring growth, IT staying flat, and AI/ML roles growing faster than general IT. foundit's March 2026 tracker also showed a split market: IT software and services declined year over year, while functional IT hiring grew.
The market is not rewarding "I know a framework" as much as it rewards engineers who can handle product constraints. Frontend and backend both work if you build that kind of depth.
Frontend usually gives faster visual feedback. You can open a browser and see your work, which makes it a friendly first step for many beginners.
Backend has fewer visual cues. You work with requests, responses, logs, data models, and failure cases. It can feel abstract earlier, but it teaches durable engineering habits quickly.
Here is the honest version:
| Area | Frontend | Backend |
|---|---|---|
| Beginner feedback | Fast and visual | Slower and more abstract |
| Hidden difficulty | Browser behavior, accessibility, state, performance | Data consistency, security, reliability, scaling |
| First portfolio | Easier to show publicly | Harder to show without product context |
| Debugging style | UI states, network calls, browser tools | Logs, traces, queries, service behavior |
| Senior growth | Product UI, platform, performance, design systems | Systems, architecture, reliability, data, security |
Frontend and backend also differ in how mistakes show up.
Frontend bugs are often visible quickly. A layout breaks, a button does not respond, a form loses input, a modal traps focus, or a page feels slow. The upside is that the feedback loop is direct. The downside is that frontend work can look "almost done" while still failing across devices, assistive technology, slow networks, or unusual data.
Backend bugs can be less visible at first and more expensive later. A bad permission check, data migration, cache invalidation bug, or retry loop may not be obvious to a user immediately, but it can affect data integrity, security, cost, or reliability.
The two paths attract different temperaments. Frontend rewards people who can handle visible product pressure and many user states. Backend rewards people who can think carefully about invisible system behavior and long-term correctness.
| Level | Frontend signal | Backend signal |
|---|---|---|
| Junior | Can build UI from existing patterns and debug with DevTools | Can build small APIs, write simple queries, and understand request flow |
| Mid-level | Can own product features with state, API calls, tests, and accessibility | Can own service changes with validation, data modeling, tests, and logs |
| Senior | Can shape UI architecture, prevent regressions, and guide frontend quality | Can shape service boundaries, reliability, security, and data correctness |
Choosing frontend or backend is not only a technology choice. It is also a trust curve. Each level asks: what kind of risk can the team trust you to handle?
AI tools can generate frontend components and backend routes quickly. That creates pressure on basic implementation work in both careers.
Frontend developers are exposed when they can only produce a visually correct first draft. They become valuable when they can verify behavior across states, devices, accessibility requirements, performance budgets, and product expectations.
Backend developers are exposed when they only copy CRUD patterns. They become valuable when they can reason about data correctness, security, concurrency, migrations, observability, and failure recovery.
AI does not remove the need for either path. It pushes both paths toward better judgment.
Frontend is likely a better fit if you:
It is also a good path if you want to become a frontend-heavy product engineer. Learn APIs well enough that you can work across the product boundary, even if your main depth is frontend.
Backend is likely a better fit if you:
Backend is also a good path if you are comfortable with slower feedback loops and more invisible work.
If you truly have no preference, start with frontend for the first few months. Build pages, forms, stateful interfaces, and API-connected projects. You will get feedback quickly, and you will learn the web platform.
Then learn backend basics: REST APIs, auth, databases, validation, error handling, and deployment. Even if you stay frontend, this knowledge will make you much better at product work. The REST API interview questions for frontend developers are a useful checkpoint.
On GreatFrontEnd, a frontend-leaning path can start with JavaScript questions, React questions, and UI coding questions. A backend-leaning product engineer should still practice system design questions and API-heavy scenarios such as Autocomplete.
After that, follow the problems you enjoy solving. If you keep caring about interaction quality, frontend is a good bet. If you keep caring about data, rules, and system behavior, backend is a good bet.
Beginners often compare the easiest frontend work with the hardest backend work, or the easiest backend work with the hardest frontend work. That creates a distorted view.
Basic frontend can look like styling pages. Professional frontend means handling browser behavior, accessibility, client state, product flows, performance, analytics, design systems, and every user state that appears after launch.
Basic backend can look like CRUD endpoints. Professional backend means data correctness, auth, migrations, observability, scaling, security, integrations, and failure handling.
Do not choose based on the easiest demo. Choose based on the difficult version you are willing to practice.
Frontend and backend are both good careers in 2026, but neither is easy by default. Frontend requires more than visual work. Backend requires more than API work. Both require careful reasoning, testing, and ownership.
Choose frontend for product-facing complexity. Choose backend for systems-facing complexity. Choose the path whose problems you are willing to keep debugging after the easy part is over.

Choose fullstack if you want broad feature ownership across UI, APIs, data, and deployment. Choose frontend if you want depth in product UI, accessibility, browser performance, design systems, and the craft of making software feel clear and reliable.
That is the short answer. The harder part is knowing which path gives you the better signal in the market you are entering.
A frontend developer is not limited to turning mockups into pages. Valuable frontend engineers can reason about UI state, network boundaries, accessibility, rendering cost, design systems, testing, observability, and the product behavior users actually experience.
A fullstack developer is not simply a frontend developer who also knows Node.js. A good fullstack developer can move a feature through the whole product path: UI, API contract, database change, auth, validation, deployment, and basic monitoring.
There is also a middle path: the frontend-heavy fullstack developer. This shows up often in startups and product teams. You do most of your work in the browser and UI layer, but you can edit backend routes, database models, and integration code when the feature needs it.
| Question | Frontend developer | Fullstack developer |
|---|---|---|
| Best fit | People who enjoy visible product work, UI detail, and browser behavior | People who enjoy owning a feature across layers |
| Main risk | Staying at the "build screens" level | Being shallow across too many areas |
| Hiring signal | Strong UI judgment, React/TypeScript, accessibility, performance, testing | Ability to ship complete features with frontend, backend, and data changes |
| Common interview areas | JavaScript, React, CSS, UI architecture, accessibility, product debugging | Frontend plus APIs, databases, auth, system design, deployment basics |
| Best company fit | Design-heavy products, SaaS, marketplaces, consumer apps, design systems teams | Startups, small teams, internal tools, product engineering teams |
| AI-era advantage | Verifying generated UI, edge states, accessibility, and behavior | Turning ambiguous product needs into working end-to-end features |
Frontend is the better path if you care about how users experience the product. That includes layout, interaction, error states, loading states, keyboard behavior, screen reader behavior, latency, and visual consistency.
Good frontend roles sit close to product and design. You may own a checkout flow, onboarding funnel, dashboard, editor, design system, or mobile web experience. The work is visible, which can be satisfying and stressful at the same time. A small bug can be obvious to everyone.
Frontend also rewards people who enjoy details. A button is rarely just a button in a serious product. It may need disabled states, loading behavior, focus styling, analytics, permission handling, optimistic updates, error recovery, responsive layout, and accessibility semantics.
This path is especially good if you want to become a:
If you are worried that frontend is getting automated, read Is Frontend Development Dying in 2026?. The short version is that basic UI output is easier to generate, but frontend judgment is still hard to replace.
Fullstack is the better path if you want to take a feature from idea to shipped behavior with fewer handoffs. You might build the form, write the API, model the database table, add validation, handle permissions, and fix the deployment issue when the first version breaks.
That range is useful in smaller companies because there may not be a clean separation between frontend, backend, infrastructure, analytics, and support tooling. A fullstack developer who can move across those boundaries can unblock a team quickly.
The tradeoff is depth. Many junior developers call themselves fullstack after learning React and one backend framework, but companies do not usually pay for labels. They pay for useful ownership. If your frontend is fragile and your backend is copied from tutorials, the title will not help.
Fullstack is especially useful if you want to:
Frontend often feels easier at the beginning because you can see the result quickly. HTML, CSS, JavaScript, and React give fast feedback. That makes it a friendly entry point for many learners.
But frontend gets hard once you leave toy projects. You need to handle browser differences, accessibility, data fetching, complex state, bundle size, design constraints, flaky networks, and many device sizes.
Fullstack can feel harder at the start because you need more moving parts. You will meet databases, HTTP, authentication, environment variables, server errors, deployment, and security concerns earlier. The learning curve is wider, but the reward is context.
If you are starting from zero, begin with frontend foundations first. Then add backend basics once you can build useful interfaces. A frontend developer who understands APIs is already ahead of many candidates.
For a quick readiness check, practice JavaScript interview questions, React interview questions, and user interface coding questions. If you are testing the fullstack direction, add system design questions after you are comfortable with APIs.
Your portfolio should match the path you want. A frontend portfolio and a fullstack portfolio can overlap, but they should not tell the same story.
For a frontend path, build evidence around:
For a fullstack path, build evidence around:
If a project claims to be fullstack but the backend is only a tutorial API, it will not help much. If a project claims to be frontend but ignores accessibility, responsive behavior, and error states, it will also look shallow.
The title alone does not decide pay. Company type, location, product complexity, interview bar, and ownership matter more.
In many startups, a fullstack developer can command strong compensation because one person can own a complete feature. In larger product companies, a frontend specialist can also earn well if they bring rare depth in performance, accessibility, design systems, or complex UI architecture.
If you are evaluating offers, do not compare only the role label. Compare:
For a deeper company-quality checklist, read How to Evaluate Companies as a Front End Engineer.
AI coding tools make simple code cheaper. They can generate components, API handlers, tests, and boilerplate quickly. That does not remove the need for engineers. It changes what good engineers are judged on.
Frontend developers need to verify whether generated UI handles accessibility, responsive behavior, loading states, browser quirks, and product edge cases.
Fullstack developers need to verify whether generated code respects data rules, auth boundaries, failure modes, and deployment behavior.
In both paths, the value moves from typing code to making correct decisions. The path you choose should match the kind of decisions you want to make every week.
| Your goal | Better first bet |
|---|---|
| Get into software through visible projects | Frontend |
| Build and launch your own app | Fullstack |
| Work closely with designers | Frontend |
| Join early-stage startups | Frontend-heavy fullstack |
| Specialize in performance or accessibility | Frontend |
| Own product features end to end | Fullstack |
| Prepare for broad startup interviews | Fullstack |
| Prepare for UI-heavy product roles | Frontend |
If you are early in your career, start with frontend well enough to build polished, accessible, tested interfaces. Then learn enough backend to understand APIs, auth, data models, and deployment.
After that, choose your depth. Go frontend if the browser and product experience keep pulling your attention. Go fullstack if you keep wanting to own the whole feature path.
Both careers are viable in 2026. The risk is staying generic. The advantage comes from becoming useful enough that a team trusts you with unclear, important work.

Frontend testing interview questions for freshers test whether you can protect user behavior, not whether you can recite tool names. Interviewers ask about unit, integration, and E2E tests through bugs: "Why did checkout break?", "Why is this test flaky?", "What would you test before merging this form?", or "Why did this snapshot fail after a harmless refactor?"
You do not need to be a testing specialist for a fresher frontend role. You should be able to design a small test plan, write one behavior-focused component test, handle async UI, avoid brittle selectors, and explain why critical flows deserve stronger tests than decorative UI.
For extra practice, try GreatFrontEnd's Test Runner coding question, the unit vs integration vs E2E quiz, and the machine coding round guide.
| Interview prompt | What the interviewer is checking | Common fresher mistake |
|---|---|---|
| "Test this login form." | User-centric selectors, validation, async submit, error state | Testing internal React state instead of visible behavior |
| "This test passes locally but fails in CI." | Flake diagnosis | Adding a longer timeout without finding the race |
| "Should this be unit, integration, or E2E?" | Cost vs confidence | Saying every critical flow needs only E2E |
| "Why avoid large snapshots?" | Signal-to-noise judgment | Treating snapshot approval as real verification |
| "How would you mock the API?" | Test boundary design | Mocking the component's internal helper instead of the network boundary |
"A login form has email, password, validation, a loading button, and an API error. What do you test?"
Test the user behavior:
That proves more than checking whether a component's internal isLoading state changed.
test('shows an error when login fails', async () => {server.use(http.post('/api/login', () =>HttpResponse.json({ message: 'Invalid credentials' }, { status: 401 }),),);const user = userEvent.setup();render(<LoginForm />);await user.type(screen.getByLabelText(/email/i), 'ada@example.com');await user.type(screen.getByLabelText(/password/i), 'wrong-password');await user.click(screen.getByRole('button', { name: /sign in/i }));expect(await screen.findByText(/invalid credentials/i)).toBeInTheDocument();expect(screen.getByRole('button', { name: /sign in/i })).toBeEnabled();});
The exact mock library can vary. The test should read like a user flow and control the API at a stable boundary.
"The test types into search and expects results immediately. It fails sometimes."
The likely bug is a timing assumption. Use findBy... or waitFor() for async results, and assert on the final user-visible result instead of sleeping for a fixed time.
"Should every cart edge case be tested in Playwright?"
No. Put pure price calculation and reducer edge cases in fast unit tests. Put cart UI state in component or integration tests. Keep E2E for the critical checkout path: add item, update quantity, enter address, reach payment or order review.
"Why does
getByRole('button', { name: /submit/i })fail?"
The button may not have an accessible name, may not be a real button, may be hidden from the accessibility tree, or may be rendered later. That test failure can reveal a usability problem.
Frontend testing checks whether UI code behaves correctly for users. It covers pure functions, components, browser interactions, network states, accessibility basics, and full user flows.
Good frontend tests catch regressions before users do. They should also be readable enough that future engineers can tell what behavior is protected.
Unit tests check a small isolated piece, such as a formatter or reducer. Integration tests check multiple pieces working together, such as a form component that validates input and calls a submit handler. E2E tests run in a browser and test a user flow across the app.
The tradeoff is speed versus confidence. Unit tests are fast and focused. E2E tests are slower but catch routing, browser, and backend integration issues.
Add this detail: Give an example for the same feature. Price formatter: unit. Cart component plus store: integration. Add-to-cart through checkout: E2E.
Start with critical user behavior: form validation, submit success and failure, rendering loaded data, empty states, error states, and navigation for core flows.
Do not start by snapshotting every component. A few behavior-focused tests protect the product with less churn than many tests that break on harmless markup changes.
Priority rule: Test the behavior that would embarrass the product if it broke: login, checkout, save, delete, upload, search, filtering, permissions, and error recovery.
The testing pyramid suggests many fast unit tests, fewer integration tests, and a smaller number of E2E tests.
Frontend teams adjust this into a more balanced shape because component integration tests can give high confidence at lower cost than full E2E tests. Match test cost to product risk.
React Testing Library is a testing utility for rendering React components and querying the DOM in ways that resemble user interaction.
Its style is to test behavior through accessible output: buttons, labels, text, roles, and form controls. That makes tests less tied to internal component structure.
getByRole()?getByRole() queries elements by their accessible role and name, which is close to how assistive technologies understand the page.
For example, screen.getByRole("button", { name: /submit/i }) checks that there is an actual button users can find by name. If this query is hard to write, the UI may have an accessibility problem.
getBy, queryBy, and findBy?getBy returns an element or throws immediately. Use it when the element should already be present.
queryBy returns null when no element is found. Use it for absence assertions.
findBy returns a promise and retries for async appearance. Use it when UI changes after data loading, timers, or user interaction.
Common failure: Using getByText() immediately after a click that triggers a request. The test races the UI. Use await screen.findByText(...) when the user-visible result appears asynchronously.
user-event, and how is it different from fireEvent?user-event simulates higher-level user interactions such as typing and clicking. It can trigger multiple DOM events and checks that the interaction is possible.
fireEvent dispatches a single event. Use it for lower-level cases, but prefer user-event for most component interaction tests.
Use async queries such as findByRole() or wait helpers such as waitFor() when the DOM updates after a promise, request, or delayed state change.
await user.click(screen.getByRole('button', { name: /load users/i }));expect(await screen.findByText('Ada Lovelace')).toBeInTheDocument();
Avoid fixed sleeps. Waiting for a real condition makes the test faster and less flaky.
Mocks replace a real dependency with a controlled fake. Use them for network calls, timers, browser APIs, analytics, and modules that are expensive or unreliable in tests.
The risk is over-mocking. If every dependency is mocked, the test may only prove that mocks match your assumptions.
A stub provides a controlled response. A mock can also record interactions so you can assert it was called with certain arguments.
For frontend tests, name the boundary you are replacing: network, module, callback prop, or browser API.
For component tests, yes, but prefer mocking at the network boundary instead of mocking internal functions. Tools such as Mock Service Worker let the component still execute its real data-fetching path while the network response is controlled.
For E2E tests, teams may use a test backend, seeded data, or network mocks depending on reliability and cost.
Why this matters: If you mock fetchUsers() directly, a later refactor from fetchUsers() to userClient.list() can break the test even though the user flow is unchanged. Mocking GET /api/users keeps the test tied to the API contract instead of component internals.
Snapshot testing saves a rendered output and compares future output against it. It can catch unexpected structural changes.
For frontend components, large snapshots are noisy. Use snapshots sparingly for stable, small outputs. Behavior tests fit buttons, forms, and user flows.
Snapshot answer: Snapshots work when the output is intentionally stable and reviewable. They fail when the reviewer cannot tell whether the diff is meaningful.
Coverage measures how much code was executed during tests. Common metrics include line, branch, function, and statement coverage.
Coverage is a signal, not a goal by itself. A project can have high coverage and still miss critical behavior if tests assert the wrong thing.
Flaky tests pass sometimes and fail other times without code changes. Common causes include timing assumptions, shared state, uncontrolled network calls, test order dependence, random data, and brittle selectors.
Fix flakes quickly. A flaky test suite trains the team to ignore failures.
Debug checklist: Look for missing await, uncontrolled timers, shared test data, test order dependence, network calls hitting real services, animations, and selectors that match multiple elements.
Test it like a user: find fields by label, type values, submit the form, and assert validation messages, disabled states, loading states, or the success result.
Avoid checking internal state variables. The user cannot see those; the test should verify behavior.
Make the dependency fail, then assert what the user sees. For example, mock the API to return 500, submit the form, and assert that an error message appears and the retry button remains usable.
Error states are worth testing because they are easy to forget during happy-path development.
Use a delayed promise or controlled network mock, trigger the fetch, assert the loading UI appears, then resolve the request and assert the final UI.
The key is to test the transition, not only the final state.
E2E testing runs the app in a real browser and checks a complete user journey, such as signup, login, checkout, or creating a dashboard item.
Playwright and Cypress are common tools. E2E tests catch routing, browser behavior, network, storage, and integration problems that unit tests cannot.
Cover the flows where a regression would hurt users or revenue: login, checkout, onboarding, billing, content creation, destructive actions, and core search or filtering.
Do not put every small component state into E2E. That makes the suite slow and brittle.
Good E2E candidates: signup, login, checkout, project creation, billing update, file upload, permission-protected route, and a destructive action with confirmation.
Visual regression testing compares screenshots across builds to detect unintended visual changes.
It fits design systems, marketing pages, dashboards, and components where layout is part of the contract. It should not replace semantic behavior tests.
Accessibility testing checks whether users with different input methods and assistive technologies can use the UI. Automated tools can catch missing labels, contrast issues, invalid ARIA, and some semantic problems.
Automated accessibility tests catch only part of the problem. Keyboard testing and screen reader checks still matter for core flows.
Prefer accessible selectors: role, label text, placeholder when it is the visible cue, visible text, and alt text. Use data-testid only when there is no stable user-facing selector.
Avoid CSS class selectors for behavior tests because styling classes are not the behavior contract.
Selector priority in practice: Role with accessible name, label text for form fields, visible text for content, alt text for images, and data-testid for UI with no user-facing label such as virtualized rows or canvas-backed controls.
Use renderHook() when the hook has logic worth testing independently, such as debouncing, timers, local storage, or data transformations.
If the hook mostly wires UI behavior, testing the component that uses it may give more confidence.
Both are JavaScript test runners. Jest is mature and common in many existing React projects. Vitest is popular in Vite-based projects because it is fast, ESM-friendly, and integrates well with Vite config.
In interviews, the exact tool matters less than knowing assertions, mocks, async tests, setup files, and test environments.
jsdom is a JavaScript implementation of many browser DOM APIs used in Node-based tests. It lets component tests render and interact with DOM-like elements without launching a real browser.
It is fast, but it is not a full browser. For layout, browser engines, clipboard behavior, downloads, and cross-browser issues, use real browser tests.
Fake timers let tests control time-based functions such as setTimeout, setInterval, and debounce logic. They make timer tests fast and deterministic.
Be careful with user interactions and promises. If the tool needs timer advancement, configure it explicitly rather than adding arbitrary sleeps.
CI testing runs tests automatically on pull requests or commits. It catches failures before code merges.
A typical setup runs linting, type checks, unit tests, and component tests on every PR. E2E and visual tests may run on release branches or deployment previews depending on cost.
Test-driven development means writing a failing test first, then writing the code to pass it, then refactoring.
Freshers do not need to claim they always use TDD. Use TDD for pure functions, reducers, bug fixes, and well-defined behavior; exploratory UI work may start with implementation and add tests once behavior stabilizes.
Do not test library internals, implementation details, trivial getters, generated code, or behavior already guaranteed by a trusted framework.
Test your decisions: validation rules, conditional rendering, state transitions, API handling, permissions, edge cases, and critical user journeys.
Good phrasing in interviews: "I would not test React's ability to call onClick; I would test what our app does after the user clicks."
Avoid tests that inspect component state, private functions, or class names unless that is the public contract. Test what the user can see or do.
Snapshots are easy to create and easy to ignore. Use them only when the output is small and stable.
await new Promise((r) => setTimeout(r, 1000)) makes tests slow and flaky. Wait for the UI condition you expect.
Mocks help at stable boundaries such as network, time, storage, and analytics. Too many mocks disconnect tests from the behavior users depend on.
Write tests for a small signup form:
409 email conflict shows "Email already exists".Use label/role queries, user-event, and an API mock. After writing the tests, explain which one is unit, which one is integration, and what single E2E test you would add for signup.
Frontend testing fresher interviews are less about naming every tool and more about explaining why a test gives confidence. Start with user behavior, then choose the smallest test that protects it.

REST API interview questions for frontend devs test whether you can turn an API contract into a reliable UI. The interview checks which method you call, how you handle status codes, what the loading and error states look like, how auth is sent, why CORS fails in the browser, and how you avoid duplicate or stale requests.
Freshers do not need to design a large backend system. You should know how a browser sends requests, what fetch() actually resolves or rejects on, why GET should not mutate data, and how frontend UI should respond to common API states.
If you want more practice around async JavaScript, pair this guide with GreatFrontEnd's JavaScript interview questions.
Backend interviews may go deep into resource modeling and database consistency. Frontend interviews care about the client contract:
| Interview prompt | What the interviewer is checking | Common fresher mistake |
|---|---|---|
| "Implement save profile." | PATCH, validation errors, disabled submit, stale UI update | Treating all failures as "Something went wrong" |
"Why didn't fetch() go to catch on 404?" | Fetch API behavior | Assuming HTTP errors reject the promise |
| "The request works in Postman but fails in the browser." | CORS and credentials | Debugging React code before checking CORS headers |
| "Should search use GET or POST?" | Method semantics, URL shareability, body size/privacy | Saying "POST is more secure" without explaining URLs |
| "User double-clicks Pay. What protects us?" | Duplicate submission and idempotency | Only disabling the button and ignoring backend guarantees |
"The user edits display name and timezone. Which API call and UI states do you handle?"
Use a partial update if the API supports it:
PATCH /api/meContent-Type: application/json{ "displayName": "Ada", "timezone": "Asia/Kolkata" }
Handle: idle, dirty, submitting, success, field validation error, auth error, conflict, and server error. Include UI behavior: disable duplicate submit, preserve user input on failure, map field errors beside fields, and refetch or update cached user data after success.
fetch() wrapper that does not lieasync function requestJSON<T>(url: string,init?: RequestInit,): Promise<T | null> {const response = await fetch(url, init);const contentType = response.headers.get('content-type') ?? '';const hasBody = response.status !== 204;const body = hasBody? contentType.includes('application/json')? await response.json(): await response.text(): null;if (!response.ok) {throw new APIError(response.status, body);}return body as T | null;}
The point is not that every app needs this exact helper. The point is that HTTP error statuses need explicit handling, and the response body may be JSON, plain text, or empty.
"The API returns data in Postman, but the frontend sees a CORS error."
Postman is not a browser and does not enforce browser CORS rules. The server must allow the frontend origin with the right CORS headers. If cookies or auth credentials are involved, the response must also satisfy credential rules; Access-Control-Allow-Origin: * cannot satisfy credentialed browser requests.
"Build product search with filters and sorting. What should the URL look like?"
For shareable, bookmarkable search, use query params:
GET /api/products?query=shoes&category=men&sort=price_asc&cursor=abc
If the filter object becomes too large or contains sensitive data, discuss a POST /search style endpoint, but name the tradeoff: URL shareability and HTTP caching become less straightforward.
"A user double-clicks Pay. Is disabling the button enough?"
No. Disabling the button improves the UI, but the backend should still protect the operation. Use an idempotency key or server-side duplicate protection for operations such as payments and order creation.
Frontend-only prevention fails when the user refreshes, retries, has two tabs open, or the network repeats a request.
A REST API exposes resources through URLs and uses HTTP semantics to operate on those resources. A frontend might call GET /products to list products, GET /products/123 to read one product, or POST /orders to create an order.
REST is an architectural style, not a single JavaScript library. In interviews, keep the answer tied to HTTP methods, resources, stateless requests, status codes, and representations such as JSON.
Interview-ready add-on: Explain one concrete resource. "Products are resources, so reading one product is GET /products/:id; creating an order is POST /orders; updating my profile can be PATCH /me."
HTTP is the protocol: methods, headers, status codes, request bodies, response bodies, caching, and authentication headers. REST is a style for designing APIs that commonly uses HTTP well.
A REST-like API should make resources and actions understandable through HTTP instead of hiding everything behind one generic endpoint.
GET reads data. POST creates or triggers processing. PUT replaces a resource. PATCH partially updates a resource. DELETE removes a resource. OPTIONS is used by browsers for CORS preflight checks.
Official reference: HTTP request methods on MDN.
GET and POST?GET retrieves a resource and should be safe, meaning it should not intentionally change server state. Query parameters are part of the URL and can be cached, bookmarked, logged, and shared.
POST sends data for the server to process, such as creating a resource or performing an action. Use POST for form submissions, login attempts, and operations with bodies that should not be placed in the URL.
Frontend trap: Do not say "POST is secure and GET is not." Security depends on HTTPS, auth, server handling, logs, and what data is exposed. The key distinction is method semantics and URL visibility.
PUT and PATCH?PUT replaces the full resource at the target URL when the API follows standard REST semantics. If you send a user object with PUT /users/1, the server treats that representation as the new full state.
PATCH applies a partial update. For example, PATCH /users/1 with { "timezone": "Asia/Kolkata" } updates only that field if the API contract says so.
An operation is idempotent if repeating the same request has the same intended effect as sending it once.
GET, PUT, and DELETE are idempotent by HTTP semantics. POST is not idempotent by default because sending it twice may create two orders, two payments, or two records.
A safe method is intended only to retrieve information and not change server state. GET and HEAD are safe.
Safe does not mean "no logs or analytics happen." It means the client did not request a state-changing operation.
Status codes are grouped by first digit:
1xx: informational2xx: success3xx: redirection4xx: client error5xx: server errorOfficial reference: HTTP response status codes on MDN.
200, 201, and 204?200 OK means the request succeeded and returns a response body in most JSON API flows.
201 Created means a resource was created. APIs may include a Location header or response body with the created resource.
204 No Content means the request succeeded but there is no response body, commonly after delete or update operations.
400, 401, and 403?400 Bad Request means the request is invalid, such as malformed JSON or missing required data.
401 Unauthorized means authentication is missing or invalid. Despite the name, it is about authentication.
403 Forbidden means the server understood who you are, but you do not have permission for that resource or action.
UI mapping: 400 maps to form or request correction in many APIs. 401 may trigger login. 403 should show a permission message or hide the action if the user truly cannot perform it.
404?Return 404 Not Found when the requested resource does not exist or should not be revealed to the current user.
For frontend UI, 404 maps to an empty detail state, a not-found page, or a redirect to a safer listing page.
409 Conflict?409 Conflict means the request conflicts with the current state of the resource. Examples include duplicate usernames, editing an outdated version of a document, or trying to reserve an already-booked slot.
The frontend should show a specific message and ask the user to refresh, change input, or retry with updated data.
429 Too Many Requests?429 means the client has hit a rate limit. APIs may include a Retry-After header telling the client when to try again.
The frontend should slow down, disable repeated actions, show a helpful message, or schedule a retry only when appropriate.
fetch() handle HTTP errors?fetch() rejects for network-level failures, not for HTTP error status codes like 404 or 500. If the server responds, the promise resolves with a Response.
Check response.ok or response.status before reading the body as success.
const response = await fetch('/api/products');if (!response.ok) {throw new Error(`Request failed: ${response.status}`);}const data = await response.json();
Official reference: Using the Fetch API.
What to say in the room: "I handle two failure classes: network/request failures through catch, and HTTP failures through response.ok or response.status."
response.ok mean?response.ok is true when the HTTP status is in the 200 to 299 range. It is false for redirects that are not followed, client errors, and server errors.
Official reference: Response.ok.
Headers are metadata sent with requests and responses. Common request headers include Content-Type, Accept, and Authorization. Common response headers include Cache-Control, ETag, Set-Cookie, and CORS headers.
Frontend developers should know which headers are safe to set from browser JavaScript and which are controlled by the browser.
Content-Type?Content-Type tells the receiver the media type of the body. JSON requests use Content-Type: application/json.
Without the right Content-Type, the server may not parse the body correctly.
Accept header?Accept tells the server which response formats the client can handle. For a JSON API, the client may send Accept: application/json.
Many APIs return JSON by default, but naming the expected format makes the contract clearer.
CORS is a browser security mechanism that lets a server decide which origins can read its responses from frontend JavaScript.
If a React app on https://app.example.com calls https://api.example.com, the API must send the right CORS headers. Otherwise the browser blocks JavaScript from reading the response.
Official reference: CORS on MDN.
Debug signal: If the browser console says CORS, changing React state management will not fix it. Check request origin, method, custom headers, credentials mode, and server response headers.
A preflight is an OPTIONS request the browser sends before some cross-origin requests. It asks the server whether the actual method and headers are allowed.
You see preflights for requests with methods like PUT or DELETE, custom headers, or non-simple content types.
Common approaches include cookies with server sessions and tokens sent through the Authorization header. In browser apps, secure cookie-based auth is common because cookies can be HttpOnly, which prevents JavaScript from reading them.
If using bearer tokens, avoid storing long-lived secrets in unsafe places. The frontend can send a token, but it cannot truly hide one from the user if JavaScript can read it.
Official reference: Authorization header on MDN.
Cookies are sent automatically on same-origin browser requests. For cross-origin fetch() calls, the request also needs the right credentials option, cookie attributes, and CORS response headers.
Bearer tokens are sent manually in an Authorization: Bearer ... header. They are flexible for APIs, but frontend storage choices matter because XSS can steal tokens available to JavaScript.
Pagination splits large lists into smaller responses. Page-based pagination uses page and limit. Cursor-based pagination uses a pointer such as nextCursor.
Cursor pagination fits feeds and frequently changing data because it avoids missing or duplicating items when records are inserted between page requests.
Frontend behavior to mention: Keep previous items while loading more, prevent duplicate "load more" clicks, handle the end of the list, and make refresh behavior explicit.
Filtering narrows the result set, and sorting controls order. A frontend might call:
GET /products?category=shoes&sort=price_asc
Keep query parameter names stable and predictable. The UI should encode user choices into the URL when those choices are shareable.
API versioning lets the backend change contracts without breaking existing clients. Common strategies include /v1/products, custom headers, or compatibility windows.
Frontend developers should know which version they call and what migration plan exists before relying on new fields.
HTTP caching stores responses so future requests can reuse them. Important headers include Cache-Control, ETag, and conditional request headers such as If-None-Match.
Caching can happen in the browser, CDN, framework, or application data layer. Stale UI bugs come from checking the wrong cache.
Official reference: HTTP caching on MDN.
ETag and 304 Not Modified?An ETag is a validator for a specific representation of a resource. The browser or client can send it back with If-None-Match.
If the resource has not changed, the server can return 304 Not Modified, allowing the client to reuse its cached copy.
Handle errors by category. Validation errors should show field messages. Auth errors should route to login or show permission messaging. Rate limits should slow retries. Server errors should show a retry option or fallback state.
Do not show raw backend stack traces. Do log enough context for debugging, such as endpoint, status code, and request ID if available.
Useful error map:
| Status | UI response |
|---|---|
400 / 422 | Show field-level validation messages when available |
401 | Ask the user to sign in again |
403 | Explain missing permission or hide the restricted action |
404 | Show not-found or empty detail state |
409 | Ask user to refresh, choose another value, or resolve conflict |
429 | Slow down retries and show rate-limit messaging |
500 | Show retry/fallback and log request context |
Disable the submit button while the request is in flight, show progress, debounce repeated clicks when appropriate, and make the backend operation idempotent when duplicate requests are dangerous.
For payments and order creation, the API should still support idempotency keys or another duplicate-protection strategy.
A frontend-friendly API contract has stable field names, clear status codes, predictable error shapes, pagination metadata, documented nullability, and enough data to render the UI without extra avoidable requests.
For mutations, it should define what the response returns, whether the client should refetch, and how validation errors map to fields.
Ask this in interviews: "Can I assume this endpoint returns the updated resource after mutation, or should the client refetch?" That one question prevents many stale UI bugs.
fetch()fetch() resolves for many HTTP error responses. Always check response.ok or response.status.
URLs can be logged, cached, shared, and stored in browser history. Use request bodies and secure auth mechanisms for sensitive data.
GET for mutationsGET should be safe. Do not create orders, delete items, or trigger payment actions through GET.
Validation, auth, permission, not-found, conflict, rate-limit, and server errors need different UI responses.
Design the frontend contract for a profile settings page:
GET /api/me loads the current profile.PATCH /api/me updates displayName, timezone, and avatarUrl.400 or 422 returns field errors.401 means the session expired.409 means the display name is taken.Then write a small fetch() helper that checks response.ok, parses JSON only when the response is JSON, handles empty responses such as 204, and throws an error object with status and body. That exercise covers more interview value than memorizing every status code.
REST API interviews for frontend freshers are about contracts and UI behavior. Explain the HTTP concept, then say how the browser UI should respond.

In fresher Next.js interviews, the prompt is a small React product problem: choose the right route files, keep secrets on the server, add the minimum client JavaScript, handle missing data, and explain why one page should be static while another must be request-time.
Definitions alone do not prepare you for those prompts. Tie App Router, Server Components, caching, and Route Handlers to product tasks: "Build a product detail page", "Why did this hydration error happen?", "Where should this API key live?", or "Why is this dashboard showing stale data?"
If your React basics are shaky, pair this guide with GreatFrontEnd's React interview questions and the React Interview Playbook.
| Interview prompt | What the interviewer is checking | Common fresher mistake |
|---|---|---|
"Build /products/[id] and show a 404 for missing products." | Dynamic routes, params, server fetching, notFound(), metadata | Rendering a generic empty div instead of a route-level not-found state |
| "Add a cart button to a server-rendered product page." | Server/Client Component boundary | Marking the whole page as "use client" instead of isolating the button |
| "This page uses an API key. Where should the request happen?" | Secret handling and server-only code | Calling the private API directly from a Client Component |
| "Why does this date cause a hydration error?" | Server HTML must match initial client render | Rendering new Date() or Math.random() directly in shared markup |
| "Product prices changed, but the page still shows old data." | Caching, revalidation, dynamic rendering | Saying "clear browser cache" without checking Next.js data/server caches |
Use this structure for most answers:
page.tsx, layout.tsx, route.ts, generateStaticParams(), notFound(), redirect(), "use client", or fetch() options.For 2026 interviews, use App Router vocabulary by default. If the interviewer asks about pages/, getStaticProps, or getServerSideProps, answer it as Pages Router knowledge and then explain the App Router equivalent.
"A product detail page is server-rendered. Marketing wants it fast for SEO, but price and stock change every few minutes. How would you build it?"
Separate stable and volatile data. Product title, description, images, and SEO metadata can be cached or statically generated. Price and stock may need short revalidation, tag-based revalidation after catalog updates, or request-time fetching if showing stale values would be harmful.
The mistake is treating the whole page as one rendering mode. Next.js lets you split the problem: keep the mostly static shell fast, then choose explicit freshness rules for the data that changes.
"The product page is a Server Component, but the Add to Cart button needs click state. What do you do?"
Keep the page as a Server Component and move only the interactive button into a Client Component.
// app/products/[id]/page.tsxexport default async function ProductPage({params,}: {params: Promise<{ id: string }>;}) {const { id } = await params;const product = await getProduct(id);return (<><h1>{product.name}</h1><AddToCartButton productId={id} /></>);}
Do not move the whole route to the client. Put the client boundary at the smallest component that needs browser behavior.
"Should
/search?q=reactbe statically generated?"
Probably not as a fully static page for every possible query. The route can render a reusable shell, but results depend on searchParams, user input, ranking, and freshness. Explain whether the results should be fetched on the server for SEO/shareable URLs, on the client for highly interactive filtering, or through a mix.
Mention loading, empty, and error states. Search pages fail interviews when candidates only talk about routing and forget the UI states users will actually see.
"A logged-out user visits
/dashboard. Where should the redirect happen?"
If the server can know from cookies that the user is logged out, redirect before rendering protected UI. Depending on the app, that can happen in server route logic or Proxy for broad route gates.
Do not rely only on useEffect(() => router.push('/login')). That flashes protected UI and ships dashboard JavaScript to a user who should not see it.
"The server renders light theme, but the client reads
localStorage.themeand switches to dark during hydration. Why is React warning?"
The first client render does not match the server HTML. Fix it by making the initial render deterministic, delaying browser-only reads until after hydration, using a cookie-backed theme available to the server, or rendering a small client theme boundary that handles the mismatch intentionally.
The word "hydration" alone does not answer the question. Name the mismatch and fix the first render.
Next.js is a React framework for building web applications. It adds routing, server rendering, static generation, data fetching patterns, image optimization, metadata handling, API route handlers, and deployment conventions around React.
Plain React mainly gives you the UI layer. Next.js decides how routes are mapped to files, how pages are rendered, how data can be fetched on the server, and how the app is bundled and optimized.
Say why: If asked "Why use it?", give a product reason: server-rendered pages for SEO, route-based code splitting, safer server data access, built-in metadata, and deployment conventions. Avoid saying only "because it improves performance"; name which part improves and why.
Official reference: Next.js App Router docs.
React is a library for building component-based UI. Next.js is a framework that uses React and adds application structure.
In a React app built with Vite, you choose your own router, data fetching setup, rendering model, and deployment pattern. In Next.js, file-system routing, server rendering, code splitting, metadata, and production build behavior come with the framework.
The App Router is the modern Next.js router based on the app/ directory. It uses React Server Components, layouts, nested routing, loading UI, error boundaries, route handlers, and streaming.
For example, app/products/page.tsx maps to /products, and app/products/[id]/page.tsx maps to dynamic product pages.
What to mention in 2026: App Router is the default mental model for new Next.js work. The Pages Router still exists, but App Router answers should use page.tsx, layout.tsx, Server Components, Route Handlers, and cache/revalidation APIs instead of starting with getStaticProps.
File-based routing means the folder and file structure defines the URL structure. In the App Router, a route segment becomes public only when it contains a page.tsx or page.js file.
For example:
app/page.tsxabout/page.tsxblog/[slug]/page.tsx
This creates /, /about, and /blog/:slug.
page.tsx, layout.tsx, and template.tsx?page.tsx renders the UI for a route. layout.tsx wraps a route segment and its children, and it is preserved across navigation when possible. template.tsx also wraps children, but it creates a new instance on navigation, so state inside it is reset.
Use layouts for shared shells like navbars and sidebars. Use templates when each navigation should remount that wrapper.
Dynamic routes handle URLs whose segment values are not known ahead of time. In the App Router, a folder like [slug] captures a value and passes it through params.
export default async function BlogPost({params,}: {params: Promise<{ slug: string }>;}) {const { slug } = await params;return <article>{slug}</article>;}
Catch-all routes use [...slug], and optional catch-all routes use [[...slug]].
generateStaticParams()?generateStaticParams() tells Next.js which dynamic routes to generate at build time. It replaces getStaticPaths from the Pages Router.
For example, a blog can fetch all slugs during the build and return { slug } objects. Next.js then pre-renders those pages instead of waiting for a first request.
Official reference: generateStaticParams.
Server Components render on the server and do not send their component code to the browser. They are the default in the App Router.
Use them for reading files, querying databases, fetching data with secrets, rendering static content, and reducing client-side JavaScript. They cannot use browser-only APIs, event handlers, or hooks like useState.
How it appears in interviews: "Why can't I add onClick here?" or "Why is window undefined?" The answer is that the component is rendering on the server, not in the browser. Add a Client Component only for the interactive part.
Official reference: Server and Client Components.
Client Components are React components that can run in the browser. Add the "use client" directive at the top of the file to mark a client boundary.
Use Client Components for state, event handlers, effects, browser APIs, focus management, animations that require browser state, and interactive forms.
"use client"?Use "use client" when the component needs client-only behavior: useState, useEffect, useReducer, DOM events such as onClick, or APIs such as window and localStorage.
Do not add "use client" to every file. Once a file is marked as a Client Component, its imported child components are part of that client bundle unless separated by server boundaries. Keeping static and data-heavy UI on the server reduces shipped JavaScript.
Yes. A Server Component can render a Client Component and pass serializable props to it. This is the common pattern for mixing server-rendered data with small interactive widgets.
A Client Component cannot directly import a Server Component, because client code runs in the browser. You can pass a Server Component as children to a Client Component from a server parent.
In Server Components, you can use async components and fetch directly on the server:
export default async function Page() {const response = await fetch('https://api.example.com/products');const products = await response.json();return <ProductList products={products} />;}
In Client Components, fetch with a client-side library or a custom hook when the data depends on browser interaction, local state, or live updates.
Trap: Server-side fetch() in Next.js is not always the same as browser fetch(). Next.js can add caching and revalidation behavior on the server. If the page must always be fresh, say so explicitly with the relevant cache option or rendering choice.
Official reference: Fetching Data.
Static rendering prepares HTML ahead of time and can be served quickly. Dynamic rendering creates the response at request time, which is needed when output depends on request-specific data such as cookies, headers, search params, auth state, or uncached data.
A fresher-friendly rule: use static rendering for public content that can be reused, and dynamic rendering for personalized or request-dependent content.
ISR means Incremental Static Regeneration. It lets static output be refreshed after a configured time or after an explicit revalidation event.
In the App Router, do not treat ISR as only the older Pages Router revalidate option. You will see fetch() cache options, revalidatePath(), revalidateTag(), and, in newer Next.js 16 codebases, Cache Components APIs such as "use cache" and cache tags.
Next.js has multiple caches. Route output, cached async work, server fetch() results, and client navigation data can all have different freshness rules.
You may see server fetch() caching controlled with cache: "force-cache", cache: "no-store", or next: { revalidate }. You may also see Cache Components controlled with "use cache", cacheLife(), cacheTag(), and updateTag(). The interview answer should name the cache and the freshness rule instead of saying "Next.js caches it."
Debugging answer: Name which cache you suspect. "Is the stale value from browser HTTP cache, Next.js server data cache, generated route output, client router cache, or our own data library?" That question beats guessing at one cache blindly.
Official reference: Caching.
loading.tsx?loading.tsx defines loading UI for a route segment. Next.js can show it while the route or a nested part of the route is loading.
It supports streaming because the user can see part of the page while slower server work continues.
error.tsx?error.tsx defines an error boundary for a route segment. It catches uncaught runtime errors from that segment and lets you render a fallback UI.
In the App Router, error.tsx must be a Client Component because error boundaries use client-side React behavior.
not-found.tsx?not-found.tsx defines the UI for a route segment's 404 state. You can trigger it by calling notFound() from next/navigation.
Use it when the route exists but the resource does not, such as /blog/missing-slug.
Route Handlers let you create API endpoints inside the App Router using route.ts or route.js. They support HTTP methods such as GET, POST, PUT, and DELETE.
export async function GET() {return Response.json({ ok: true });}
They fit webhooks, BFF endpoints, auth callbacks, and server-only operations that the browser should not implement directly.
Server Functions are async server-side functions marked with the "use server" directive. In form submissions or mutation flows, they are called Server Actions.
For a fresher interview, explain the idea carefully: the browser submits data, but the trusted mutation logic runs on the server.
A Route Handler exposes an HTTP endpoint. Other clients can call it if they know the URL and have permission.
A Server Action is a server function integrated with React and Next.js for form and mutation flows. Use Route Handlers for external HTTP APIs and webhooks. Use Server Actions for app-owned mutations tied to UI flows.
SSR renders HTML on the server for each request. SSG creates HTML at build time. CSR sends a JavaScript app shell and renders mainly in the browser. ISR serves static output but regenerates it after revalidation.
Next.js can mix these patterns route by route and even within a route when streaming and caching are involved.
Hydration is the process where React attaches event handlers and client-side behavior to HTML that was already rendered on the server.
Server-rendered HTML can be visible before it is interactive. Client Components need hydration before clicks, inputs, and stateful behavior work.
Hydration errors happen when the HTML rendered on the server does not match what React expects on the client.
Common causes include rendering Date.now() or Math.random() directly in markup, reading window during server render, changing output based on browser-only state, invalid HTML nesting, or mismatched data between server and client.
How to fix it: Make the initial server and client render match. Move browser-only reads to an effect, pass server-known values through cookies or props, or isolate the unstable UI in a Client Component that renders a stable placeholder first.
next/link used for?next/link enables client-side navigation between routes. It avoids a full page reload and can prefetch route data when links are likely to be visited.
Use <Link href="/dashboard">Dashboard</Link> for internal navigation. Use a normal <a> for external links.
useRouter() used for?useRouter() is used in Client Components for programmatic navigation, such as redirecting after a user clicks a button or completes a client-side interaction.
In Server Components, use server-side helpers such as redirect() from next/navigation instead.
In the App Router, you can export a static metadata object or an async generateMetadata() function from a page or layout.
Use static metadata when the title and description are known. Use generateMetadata() when metadata depends on params or fetched data.
Official reference: generateMetadata.
next/image?next/image is Next.js's image component. It handles image sizing, optimization, lazy loading, and layout stability when used correctly.
Interviewers ask about it because images are among the largest page assets, and a framework image component can reduce layout shift and improve loading behavior.
next/font?next/font loads and optimizes fonts. It can self-host supported fonts and reduce layout shift by generating font-related CSS during the build.
Use it instead of manually adding third-party font <link> tags when possible, because font loading affects performance and visual stability.
Proxy is the modern name for what older Next.js versions called Middleware. A proxy.ts file can run before a request completes and can redirect, rewrite, set headers, read cookies, or respond early.
Use it for request-level logic such as auth redirects, locale routing, and header changes. Do not put heavy application logic there.
Auth nuance: Proxy runs before route rendering, so it works for broad request decisions. It is not a replacement for server-side authorization inside data access or mutations. If the dashboard route is protected, both the route and the backend operation should still enforce permission.
Official reference: proxy.js file convention.
Server-only environment variables are available to server code and should be used for secrets such as API keys. Variables prefixed with NEXT_PUBLIC_ are bundled for the browser and must not contain secrets.
The interview trap is treating every environment variable as secret. Anything sent to client JavaScript can be viewed by users.
Authentication involves a session cookie or token, server-side validation, and route protection. Server Components can read request data such as cookies, Route Handlers can implement auth callbacks, and Proxy can redirect unauthenticated users before rendering.
Avoid trusting only client-side checks. The server must protect sensitive data and mutations.
redirect() and client-side navigation?redirect() from next/navigation is used during server rendering or server logic to stop rendering and send the user to another route.
Client-side navigation with router.push() happens in a Client Component after browser interaction. Use the server redirect when the server already knows the user should not see the current route.
The standard production flow is to run next build, then host the generated server output on a platform that supports the chosen Next.js features. Vercel supports Next.js features directly, but Next.js can also run on Node-based hosts and other platforms with the right adapter or deployment setup.
Freshers should know that a static-only export cannot support every server feature. Server rendering, Route Handlers, Server Actions, and request-time data need a runtime.
Build one small app with public pages, a dynamic detail page, a form, a Route Handler, metadata, a loading state, and a protected dashboard. That is enough to discuss most junior Next.js topics.
Practice with a mini product catalog or blog: list page, detail page, search params, server-fetched data, a client filter, a form mutation, and a small auth gate.
Next.js supports multiple rendering patterns. A page might be statically generated, dynamically rendered, partially streamed, hydrated on the client, or driven by client-side data after the first load.
"use client" everywhereThis removes many benefits of Server Components. Add "use client" at the smallest boundary that needs browser behavior.
getStaticProps, getServerSideProps, and getStaticPaths belong to the Pages Router. In the App Router, learn Server Components, fetch() options, generateStaticParams(), generateMetadata(), Route Handlers, and cache revalidation APIs.
Server Components and Route Handlers can access secrets. Client Components cannot keep secrets because their JavaScript is sent to the browser.
Build a small product catalog:
/products lists products and has a loading state./products/[id] fetches a product on the server and calls notFound() when missing.AddToCartButton is the only Client Component on the detail page.POST /api/cart is implemented as a Route Handler or app-owned mutation path.When explaining the solution, say which parts run on the server, which parts hydrate, which data can be cached, and where secrets would live. That is the real interview signal.
Next.js fresher interviews become clearer when you explain each feature by execution location: server, client, build, or request boundary. That mental model prevents most wrong answers.

Redux interview questions for freshers test whether you can choose and explain a state model, not whether you memorized the phrase "single source of truth." Connect the UI problem to Redux's data flow: state lives in a store, the UI dispatches events, reducers calculate the next state, and components read only the data they need.
In 2026, answer Redux questions with Redux Toolkit as the default. Older tutorials show hand-written action types, createStore(), switch-heavy reducers, and lots of boilerplate. You should still understand those ideas, but modern Redux code normally uses configureStore(), createSlice(), React Redux hooks, and RTK Query or thunks for async work.
If you want hands-on practice, implement Redux Store and Redux Store II on GreatFrontEnd after reading this guide.
| Interview prompt | What the interviewer is checking | Common fresher mistake |
|---|---|---|
| "The navbar cart count updates from many pages. Where should that state live?" | Shared state and component communication | Putting everything in Redux without explaining why |
| "This reducer pushes into an array. Is that okay?" | Immutability and Redux Toolkit/Immer | Saying all mutation is always wrong, even inside createSlice() |
| "Why does this component re-render on every action?" | Selector return values and reference equality | Returning a new object from useSelector() every time |
| "Should a text input use Redux?" | Local vs global state | Dispatching on every keystroke by default |
| "How do you fetch products and cache them?" | Thunks vs RTK Query vs component fetch | Writing loading reducers for every endpoint without considering server-state tooling |
"A user can add items from product pages, search results, and recommendations. The navbar badge should update everywhere."
Redux is a reasonable choice because multiple distant components need the same state and the actions are meaningful product events: cart/itemAdded, cart/itemRemoved, cart/quantityChanged. The reducer owns the cart state; selectors expose selectCartCount and selectCartTotal.
Do not stop at "Redux avoids prop drilling." Name the shared state, the events, and the derived selectors the UI needs.
"A modal has a search box. Should the input value go into Redux?"
Usually no. The typed value is temporary UI state owned by one component. Keep it in React state unless another feature needs it, the value must survive navigation, or it is part of a shareable URL.
This scenario checks judgment. Redux skill includes knowing when not to use Redux.
"Where should product list loading, error, and cached data live?"
If the app already uses Redux Toolkit, RTK Query fits this case because product data is server state: it needs fetching, caching, invalidation, and refetching. A thunk still works for custom flows, but server state and client state are different problems.
"This selector returns
{ count, total }, and the component re-renders after unrelated actions. Why?"
Returning a new object creates a new reference on every store update. Split selectors, use a memoized selector, or use an equality function when appropriate.
const count = useSelector(selectCartCount);const total = useSelector(selectCartTotal);
The interviewer is checking whether you understand React Redux's render behavior, not only Redux vocabulary.
"A user likes a post. The UI updates immediately, but the API fails. What should happen?"
Dispatch an optimistic action, keep enough information to roll back, and handle the failure action by reverting or showing a retry state. For server-state flows, use the mutation lifecycle provided by the data library.
The product detail matters: a like can be retried or reverted; a payment cannot be treated casually.
Provider, useSelector, and useDispatch?Redux is a predictable state management library for JavaScript apps. It stores application state in a single store and updates that state by dispatching actions to reducers.
In React apps, Redux fits state that many components need, state that benefits from debugging history, or server/cache state managed through Redux Toolkit Query.
Add this detail: Do not pitch Redux as "global variables for React." Say it fits state transitions that need structure, traceability, and consistent reads across distant components.
Official reference: Getting Started with Redux.
Redux solves prop chains through many component layers, shared reads across distant components, and state transitions that need a traceable action history.
It is not needed for every piece of state. Input text, modal open state, hover state, and small component-only state belong in React local state.
Example: Cart, auth session metadata, feature flags, editor document state, and cross-page notification queues have a clearer Redux payoff than a single input's current value.
The core concepts are store, actions, and reducers.
The store holds state. Actions describe what happened. Reducers receive the previous state and an action, then return the next state.
The store is the object that holds the entire Redux state tree. It lets you read state with getState(), update state with dispatch(action), and subscribe to changes.
In modern Redux, create the store with Redux Toolkit's configureStore(), not the older createStore() API.
Official reference: Redux Store API.
An action is a plain object that describes something that happened in the app. It must have a type field and may include a payload.
{type: "cart/itemAdded",payload: { id: "p1", quantity: 1 }}
Good action names describe events, not setter operations. cart/itemAdded is clearer than SET_CART.
A reducer is a pure function that calculates the next state from the previous state and an action.
function counterReducer(state = { value: 0 }, action: { type: string }) {if (action.type === 'counter/incremented') {return { value: state.value + 1 };}return state;}
Reducers should not fetch data, mutate external variables, read time randomly, or dispatch actions.
How to test this answer: A reducer should be easy to unit test with plain inputs and outputs. If the reducer needs the current time, random IDs, network data, or localStorage, that work belongs before the action is dispatched or in async/middleware logic.
Pure reducers make Redux predictable. Given the same previous state and action, the reducer should return the same next state.
This predictability enables debugging, replaying actions, testing reducers as simple functions, and understanding state changes from the Redux DevTools history.
dispatch() sends an action to the Redux store. The store runs the root reducer with the current state and the dispatched action, then stores the new state.
In React components, you normally dispatch action creators:
const dispatch = useDispatch();dispatch(cartItemAdded({ id: 'p1' }));
Redux data flow goes in one direction:
This keeps state changes from happening in many unrelated places.
Redux Toolkit is the official recommended way to write Redux logic. It includes helpers like configureStore(), createSlice(), createAsyncThunk(), and RTK Query.
It reduces boilerplate, sets up store defaults, includes development checks for common mistakes, and lets reducers use draft mutation syntax through Immer.
Official reference: Redux Style Guide.
configureStore()?configureStore() creates a Redux store with sensible defaults. It combines reducers, adds middleware, enables Redux DevTools in development, and includes checks that catch accidental mutations and non-serializable values.
import { configureStore } from '@reduxjs/toolkit';export const store = configureStore({reducer: {cart: cartReducer,user: userReducer,},});
createSlice()?createSlice() creates a slice reducer, action creators, and action types from one feature-focused definition.
const counterSlice = createSlice({name: 'counter',initialState: { value: 0 },reducers: {incremented(state) {state.value += 1;},},});
The code looks like mutation, but Redux Toolkit uses Immer to produce immutable updates safely.
Fresher trap: This does not mean "Redux allows mutation now" everywhere. The safe draft mutation applies inside Immer-powered reducers created by Redux Toolkit. Outside that boundary, keep immutable update rules in mind.
A slice is the Redux logic for one feature or domain, such as cart, auth, todos, or products. It contains initial state, reducers, generated actions, and selectors for that feature.
Feature-based slices keep related state, actions, and reducers in the same file instead of scattering one feature across action, reducer, and constant folders.
Redux Toolkit uses Immer. Immer gives your reducer a draft version of state. You write changes to the draft, and Immer produces the next immutable state behind the scenes.
This is why state.value += 1 is okay inside a createSlice() reducer but mutating state directly in a plain hand-written reducer is not okay.
Immutability means you do not change the existing state object. You return a new object or array for changed parts and reuse unchanged parts.
Redux relies on reference changes to know what changed. If you mutate the same object and return it, React Redux may not detect a change correctly.
React Redux is the official binding library that connects React components to a Redux store. It provides <Provider>, useSelector(), and useDispatch().
<Provider store={store}> makes the Redux store available to components. Hooks then read and update the store.
Official reference: React Redux hooks.
<Provider> do?<Provider> passes the Redux store through React context so any nested component can use React Redux hooks.
Without <Provider>, useSelector() and useDispatch() do not know which Redux store to use.
useSelector()?useSelector() reads a value from the Redux store. It accepts a selector function and re-renders the component when the selected value changes.
const cartCount = useSelector((state: RootState) => state.cart.items.length);
Return the smallest value the component needs. Returning a new object every time can cause unnecessary re-renders.
Bad pattern:
const cart = useSelector((state) => ({count: state.cart.items.length,total: state.cart.total,}));
This creates a new object on every store update. Prefer separate selectors or a memoized selector when returning derived objects.
useDispatch()?useDispatch() returns the store's dispatch function so a component can dispatch actions.
const dispatch = useDispatch();function onAddToCart(id: string) {dispatch(itemAdded({ id }));}
In TypeScript apps, many teams create a pre-typed useAppDispatch() hook based on the store's dispatch type.
Selectors are functions that read specific data from Redux state.
const selectCartItems = (state: RootState) => state.cart.items;
Selectors keep components from knowing the exact state shape. If the store shape changes, you update selectors rather than every component.
Memoized selectors cache derived results. Use them for filtered lists, totals, or expensive derived values from state.
Use memoization when the derived calculation is expensive or returns new arrays/objects that would otherwise cause unnecessary re-renders.
Reducers must stay pure, so async work happens outside reducers. Common options are thunks, createAsyncThunk(), RTK Query, or custom middleware.
For freshers, know the common flow: dispatch pending, perform the request, dispatch success or failure, and update state based on those actions.
How to choose: Use RTK Query for normal CRUD/server data. Use thunks for custom workflows that coordinate multiple actions, read current state, or mix API calls with client-owned state changes.
A thunk is a function that can contain async logic and dispatch actions later. Redux Toolkit includes thunk middleware by default.
export const fetchUser = (id: string) => async (dispatch: AppDispatch) => {dispatch(userRequested());const user = await api.getUser(id);dispatch(userReceived(user));};
Use thunks for app logic that needs dispatch, getState, or multiple actions around one async operation.
createAsyncThunk()?createAsyncThunk() is a Redux Toolkit helper for request-style async logic. It automatically creates pending, fulfilled, and rejected action types.
Reducers handle those cases in extraReducers, which keeps loading and error states predictable.
RTK Query is Redux Toolkit's data fetching and caching tool. It can generate hooks for queries and mutations, cache server responses, deduplicate requests, and invalidate data by tags.
Use RTK Query when the main problem is server data. Use slices and reducers when the main problem is client-owned application state.
Official reference: RTK Query overview.
Use React Context for dependency-style values such as theme, locale, or current user metadata. Use Redux when state changes frequently, many components need slices of it, debugging history matters, or update logic is complex.
Context alone does not provide reducers, middleware, DevTools history, normalized patterns, or built-in server-state caching.
Middleware runs between dispatching an action and the action reaching reducers. It can log actions, handle async functions, report analytics, or intercept certain actions.
Reducers should not have side effects. Middleware is one safe place for side-effect logic.
Redux DevTools show dispatched actions, state changes, and the current store state. They help debug why UI changed and what action caused it.
This is one reason Redux still appears in larger codebases: it gives teams a common timeline for state transitions.
Avoid putting non-serializable values such as DOM nodes, class instances, Promises, functions, and raw Date objects in Redux state. Also avoid storing tiny UI state that only one component uses.
Redux state should be serializable because DevTools, persistence, debugging, and predictable updates depend on plain data.
Reducers are easy to test because they are pure functions. Pass an initial state and an action, then assert the returned state.
For React components connected to Redux, render the component with a real test store when possible. For async data, mock the network boundary or use RTK Query testing patterns instead of testing internal implementation details.
Good reducer test shape:
expect(cartReducer({ items: [] }, itemAdded({ id: 'p1' }))).toEqual({items: [{ id: 'p1', quantity: 1 }],});
This tests the state transition rather than the implementation.
Redux is a tool for shared, traceable, complex state. A small form or one-page widget does not need it.
state.items.push(item) is only safe inside Redux Toolkit's Immer-powered reducers. In plain reducers, return a new array or object.
useSelector()If a selector returns a new object on every store update, the component can re-render on unrelated changes. Select the exact values needed or use memoized selectors.
Server state comes from the backend and needs fetching, caching, invalidation, and refetching. Client state is owned by the UI. RTK Query fits server state more directly than hand-writing loading reducers for every endpoint.
Build a mini cart state model:
cartSlice with itemAdded, itemRemoved, and quantityChanged.useSelector().itemAdded() from a product card.This small drill proves more Redux understanding than memorizing ten definitions.
For a fresher interview, a solid Redux answer has three parts: describe the data flow, state why reducers stay pure, and mention Redux Toolkit as the modern default.

Rippling frontend interview questions usually test practical React, JavaScript concurrency, schema-driven forms, API-backed admin UI, and frontend system design. Prepare to build working features quickly, run code, explain state ownership, and reason about payroll, reporting, workflow, and employee-management interfaces.
For the company-guide view, use the Rippling Front End Interview Guide alongside this article.
Use each question as a working session: ship the baseline first, then explain what changes for validation, pagination, permissions, large data, accessibility, retries, and cross-functional ownership.
Rippling is a broad enterprise SaaS product. A frontend engineer might work on onboarding, employee records, payroll, benefits, app provisioning, spend management, reports, or Workflow Studio. That product context explains why the interview loop mixes React implementation, JavaScript utilities, DSA, and frontend system design.
| Area | What to practice | Why it matters at Rippling |
|---|---|---|
| React implementation | Schema forms, paginated lists, data tables, grids, editable records, filters, workflow builders | Admin workflows are form-heavy and data-heavy. |
| JavaScript | Concurrency-limited task runner, event emitter, promise race, bind, flatten, recursive counts | Interviews check whether you can write utilities without hiding behind React. |
| API-backed UI | Cursor pagination, load more, infinite scroll, dedupe, loading/error states, optimistic updates | Rippling interfaces often read and mutate company data through APIs. |
| State modeling | Field schemas, derived validity, dependent fields, row-level edits, undo/redo, commit/rollback | Enterprise UI punishes duplicated or unclear state. |
| DSA | Trees, arrays, subarray sums, grid logic, hash maps, recursion | Some loops include a separate algorithm round. |
| Frontend system design | Employee directory, reports builder, payroll dashboard, Workflow Studio, feed or masonry layout | Senior rounds test product tradeoffs and browser architecture. |
| Behavioral | Ownership, speed, project scope, collaboration, production follow-through | Hiring-manager rounds dig into how you ship with product, design, and backend. |
The right prep is not LeetCode-only and not React-only. Rippling rewards engineers who can turn an ambiguous admin workflow into a working, testable interface.
Rippling's exact process varies by team. The company hires across many products, so a frontend-leaning role can still include backend API or general coding rounds. Treat recruiter instructions as the source of truth.
Expect a process shaped roughly like this:
| Stage | What to expect | Prep note |
|---|---|---|
| Recruiter screen | Background, motivation, role fit, compensation, team context | Ask whether the role is frontend-only or frontend-leaning full stack. |
| Technical phone screen | Live React, JavaScript utility, or API-backed UI coding | Practice on a small starter project and run code as you go. |
| Hiring manager round | Project depth, ownership, product judgment, collaboration, tradeoffs | Prepare one detailed project story with architecture, rollout, and metrics. |
| Onsite React round | Build an incremental UI feature with state, fetching, validation, tests | Expect follow-ups that add pagination, infinite scroll, dependent fields, or dedupe. |
| DSA / JavaScript round | Trees, arrays, recursion, event emitter, concurrency, flatten, bind | Keep practical JavaScript and algorithm basics warm. |
| System design round | Feed, masonry layout, reports builder, employee directory, workflow UI | Ground the answer in enterprise admin UI behavior, permissions, and large data. |
| Behavioral / team round | Cross-functional work, ownership, pace, mistakes, conflict | Prepare concrete STAR stories; avoid generic teamwork answers. |
If the loop includes a web API round, practice a small Node or Express service with CRUD endpoints, validation, error responses, and a short discussion of auth, logging, rate limits, and monitoring.
Use these as practice prompts, not a guaranteed question bank. They cover the recurring Rippling shape: practical React, async JavaScript, data-heavy admin screens, and system design.
| Rippling question or task | What to practice |
|---|---|
| Build a grid of lights in React where clicking a cell toggles its state and derived counters update. | Grid state, immutable updates, derived counts, testable components |
| Build a 2048-style board model with initialization, move logic, merge behavior, and tests. | 2D arrays, pure functions, edge cases, unit tests |
| Build a paginated list that fetches items from an API and appends the next page when the user clicks "Load more." | Fetch state, cursor tokens, dedupe, loading and error states |
Extend the paginated list with infinite scroll using IntersectionObserver and a throttled fallback. | Browser APIs, cleanup, duplicate request prevention |
| Build a schema-driven React form with text, select, checkbox, and dependent fields. | Schema modeling, controlled inputs, validation, field dependencies |
| Add form submission that returns values, validation state, and field-level errors. | Error display, submit gating, API contract, accessibility |
| Implement a task runner that executes async tasks with a concurrency limit and preserves result order. | Promises, queues, worker loops, error policy |
| Implement promise race behavior and explain how cancellation differs from ignoring stale results. | Promise timing, cleanup, AbortController, stale guards |
| Count all comments in a nested replies tree. | Recursion, iterative traversal, tree data |
| Implement an event emitter or pub/sub utility with cleanup. | Map, Set, listeners, unsubscribe, one-time handlers |
| Flatten a nested array where top-level items keep priority over deeper items. | Queue traversal, recursion vs iteration, ordering rules |
Implement Function.prototype.bind behavior for normal calls and partial arguments. | this, closures, function context |
| Solve max tree depth and subarray sum style questions. | DFS, hash maps, prefix sums, complexity |
| Build a small employee directory with search, filters, row actions, and permission-aware columns. | Admin UI, data table state, bulk actions, role-based rendering |
| Design a social feed or activity feed for company events such as hires, approvals, payroll status, and app provisioning. | Feed ranking, pagination, optimistic updates, dedupe, moderation |
| Design a masonry layout for cards with variable heights and large image or report previews. | Layout algorithms, responsive columns, virtualization |
| Design a reports builder where users pick attributes, group rows, filter columns, and drill into aggregate values. | Frontend system design, query lifecycle, preview state, cancellation |
| Design a Workflow Studio-style automation builder with trigger nodes, action nodes, step configuration, undo/redo, and execution log. | Graph UI, schema-aware forms, validation, local drafts, long-running jobs |
Rippling-shaped forms are rarely just two inputs and a submit button. Benefits enrollment, payroll setup, app provisioning, onboarding, and workflow actions all depend on field schemas, validation rules, permissions, and dependent fields.
Start with a small schema:
type FieldSchema =| {id: string;label: string;type: 'text';required?: boolean;}| {id: string;label: string;type: 'select';options: Array<{ label: string; value: string }>;required?: boolean;dependsOn?: string;}| {id: string;label: string;type: 'checkbox';};type FormState = Record<string, string | boolean>;
Then build in layers:
A good answer covers:
isValid separately when it can be derived from values and schema.Practice this with Contact Form for validation habits and Users Database for CRUD-style state.
A Rippling UI often starts as "fetch and display a list" and then grows: cursor pagination, load more, infinite scroll, dedupe, sorting, filters, and retries.
Use a state shape that separates data, cursor, and request status:
type PageItem = { id: string };type PageState<T extends PageItem> = {items: Array<T>;nextCursor: string | null;status: 'idle' | 'loading' | 'success' | 'error';errorMessage?: string;};
The fetch function should prevent duplicate in-flight requests and ignore stale responses:
let activeRequestId = 0;async function loadNextPage() {const cursor = state.nextCursor;if (state.status === 'loading' || cursor == null) {return;}const requestId = ++activeRequestId;setState((current) => ({...current,errorMessage: undefined,status: 'loading',}));try {const response = await fetchItems({ cursor });// A newer request has started, so this response should not update the UI.if (requestId !== activeRequestId) {return;}setState((current) => {const seenIds = new Set(current.items.map((item) => item.id));// Cursor APIs can overlap pages, so append only unseen records.const newItems = response.items.filter((item) => !seenIds.has(item.id));return {...current,items: [...current.items, ...newItems],nextCursor: response.nextCursor,status: 'success',};});} catch {if (requestId !== activeRequestId) {return;}setState((current) => ({...current,errorMessage: 'Could not load more items.',status: 'error',}));}}
In the interview, discuss what you would tighten in production code:
AbortController when the fetch layer supports cancellation.IntersectionObserver for infinite scroll, with a visible fallback button.Practice Job Board and Data Table until this flow feels automatic.
The concurrency-limited task runner is a compact JavaScript problem with product value. Rippling's platform work includes workflows, reports, provisioning steps, and async jobs where unbounded parallelism can overload a service.
Start with the contract:
limit tasks run at the same time.One implementation:
async function runWithConcurrency<T>(tasks: Array<() => Promise<T>>,limit: number,): Promise<Array<T>> {if (!Number.isInteger(limit) || limit < 1) {throw new RangeError('limit must be a positive integer');}const results = new Array<T>(tasks.length);let nextIndex = 0;async function worker() {while (nextIndex < tasks.length) {// Claim the next task synchronously before awaiting its result.const currentIndex = nextIndex;nextIndex += 1;results[currentIndex] = await tasks[currentIndex]();}}const workerCount = Math.min(limit, tasks.length);await Promise.all(Array.from({ length: workerCount }, worker));return results;}
Then explain follow-ups:
limit < 1.Promise.all, or collect { status, value, reason } per task.AbortSignal into tasks when the caller cancels.This is a better answer than using Promise.all(tasks.map(...)), because unbounded concurrency is the bug the prompt is trying to reveal.
Game prompts test state transitions without CSS distraction. For 2048, keep the board logic pure:
type Board = Array<Array<number>>;function compact(row: Array<number>): Array<number> {return row.filter((value) => value !== 0);}function mergeLeft(row: Array<number>): Array<number> {const values = compact(row);const merged: Array<number> = [];for (let index = 0; index < values.length; index += 1) {if (values[index] === values[index + 1]) {merged.push(values[index] * 2);// Skip the next tile because it has already been merged.index += 1;} else {merged.push(values[index]);}}while (merged.length < row.length) {merged.push(0);}return merged;}
After mergeLeft works, derive other directions by reversing or transposing the board. Add tests before UI:
[2, 0, 2, 0] -> [4, 0, 0, 0][2, 2, 2, 2] -> [4, 4, 0, 0][4, 4, 8, 0] -> [8, 8, 0, 0][2, 4, 8, 16] -> [2, 4, 8, 16]For grid-light prompts, use the same habit: pure toggle logic first, React state second. Interviewers can change the prompt quickly, and pure functions make follow-ups easier.
Rippling's engineering blog on real-time reporting is useful background because reports combine frontend attribute selection with query planning, permissions, caching, and large result sets. A frontend system design answer should not try to design the whole analytics backend. Focus on the browser contract.
Clarify scope:
Then structure the design:
| Design area | What to cover |
|---|---|
| Attribute picker | Search, grouping by product area, permissions, selected-field summary, keyboard navigation |
| Query builder | Client-side report config, validation, dependent options, disabled invalid states |
| Preview lifecycle | Debounced preview, cancellation, stale response guard, loading, empty, error, sampled preview |
| Result table | Pagination, virtualization, column resizing, sorting, drilldown, export, copy |
| Caching | Cache by report config and permission context; invalidate when filters, role, or fields change |
| Drafts | Autosave, dirty state, undo/redo, conflict behavior when another edit wins |
| Accessibility | Form labels, keyboard access, grid navigation, focus recovery after preview updates |
| Observability | Track slow previews, canceled requests, empty results, field-search misses, and export errors |
Good follow-up answers:
This is the kind of system design that feels closer to Rippling than a generic social feed.
Rippling prep should keep practical JavaScript and DSA warm at the same time.
| Topic | Practice questions |
|---|---|
| Async JavaScript | Task runner with concurrency, promise race, async memoization, retry, stale response handling |
| Events | Event emitter, pub/sub, unsubscribe cleanup, one-time listeners |
| Arrays and functions | Flatten with custom ordering, bind polyfill, grouping, dedupe by ID, array transforms |
| Trees and recursion | Count nested comments, max tree depth, tree filtering, nested menu rendering |
| Hash maps | Subarray sum, frequency counts, duplicate detection, lookup tables |
| React UI | Schema forms, data table, paginated list, grid of lights, editable rows, controlled inputs |
| System design | Reports builder, employee directory, payroll dashboard, Workflow Studio, feed, masonry layout |
Useful GreatFrontEnd practice:
Use Rippling's own product and engineering material to make system design answers concrete:
Use this as a Rippling-specific checklist. The exact order can change, but the coverage should stay the same: practical React, async JavaScript, admin UI system design, DSA, and project depth.
| Prep area | What to do | Rippling-specific angle |
|---|---|---|
| Practical React | Build schema form, paginated list, infinite scroll, data table, grid of lights, editable rows, and search/filter UI. | These map to employee records, reports, approvals, payroll setup, and onboarding workflows. |
| Async JavaScript | Implement concurrency-limited task runner, event emitter, async memoization, promise race, debounce, and retry with backoff. | Rippling screens often check whether you can control async work without library help. |
| DSA | Practice max tree depth, subarray sum, tree traversal, flatten, hash maps, and grid logic. | Some loops include a separate algorithm round. |
| Frontend system design | Design employee directory, reports builder, payroll run dashboard, Workflow Studio, and an activity feed. | Cover permissions, large data, long-running jobs, drafts, validation, and error states. |
| API-backed UI | Build a small mocked API and wire React to it with loading, empty, error, retry, pagination, and optimistic updates. | Frontend-leaning roles can still ask for web API thinking. |
| Behavioral and project depth | Prepare one deep project walkthrough and 5-7 STAR stories around ownership, speed, collaboration, conflict, and mistakes. | Hiring-manager rounds dig into what you personally owned and how you worked with other disciplines. |
| Mock loop | Run one React mock, one JavaScript utility mock, one DSA mock, one system design mock, and one project deep dive. | Fix the weakest answer after each mock. |
If you have only 72 hours, prioritize schema form, paginated list with infinite scroll, task runner with concurrency, event emitter, max tree depth, subarray sum, reports-builder system design, and your strongest project story.
Rippling frontend prep should end with one clear story: "I can take an ambiguous admin workflow and turn it into a working, testable, API-backed UI." That means the best practice set is not a random pile of React trivia. It is schema forms, paginated lists, data tables, async concurrency, event emitters, tree traversal, and product-shaped system design.

Snowflake frontend interview questions usually test JavaScript fluency, React state, grid-style UI coding, and frontend system design for data tools. Prepare for interactive components, async state, graph or dynamic-programming follow-ups, and Snowsight-shaped interfaces such as worksheets, dashboards, result grids, and AI-assisted SQL.
For the company-guide view, use the Snowflake Front End Interview Guide alongside this article.
Use each question as a working session: build the baseline, then explain what changes for keyboard input, async loading, large results, permissions, accessibility, and slow queries.
Snowflake is a data cloud company, but frontend prep should not become database-internals prep. The frontend work is closer to building a browser-based workspace for analysts, engineers, and data teams: editors, query results, dashboards, catalog search, notebooks, Streamlit apps, and AI side panels.
| Area | What to practice | Why it matters at Snowflake |
|---|---|---|
| React implementation | Checkerboards, grid games, editable tables, typeahead, tabbed workspaces, dashboard tiles | Small UI prompts reveal state ownership, event handling, and follow-up resilience. |
| JavaScript | Event emitter, debounce, throttle, promises, this, closures, arrays, maps, undo/redo | Frontend rounds often check language fluency without much library help. |
| Data rendering | Result tables, pagination, virtualization, sorting, filtering, column sizing, empty states | Snowsight users inspect query output and dashboards inside the browser. |
| Async UI | Query execution, cancellation, stale response handling, loading/error states, retries | Data tools spend a lot of time waiting on remote work. |
| Algorithms | Grid traversal, shortest path, dynamic programming, Sudoku or Tic Tac Toe validation, graph search | UI-game prompts can turn into algorithmic follow-ups quickly. |
| Frontend system design | SQL worksheet, query-result viewer, dashboard builder, autocomplete, AI code assistant | Senior loops test whether you can design the client side of a data product. |
| Behavioral | Project depth, tradeoffs, ownership, customer focus, collaboration, mistakes | Snowflake teams care about how you make decisions in ambiguous product work. |
The right prep balance is JavaScript plus practical UI. Do enough Snowflake product reading to make your system design answers concrete, but spend most of your interview practice writing and explaining code.
Snowflake's hiring process page says engineering hiring consists of four stages and can take up to two to four weeks, with variation by team and role. It also says most open jobs include phone screens and onsite or video interviews.
Expect a process shaped roughly like this:
| Stage | What to expect | Prep note |
|---|---|---|
| Recruiter screen | Background, role fit, location, timeline, and team discussion | Ask whether the first technical round is React, JavaScript, DSA, or system design. |
| Technical screen | Live coding in JavaScript, TypeScript, React, or a shared editor | Practice from a blank file without relying on autocomplete. |
| Second technical screen | UI coding, graph/grid logic, or JavaScript utility implementation | Be ready for an interactive grid prompt followed by algorithmic follow-ups. |
| Onsite coding | Practical UI build, JavaScript fundamentals, or LeetCode-style problem | Build a working baseline before optimizing. |
| Frontend system design | Data-tool UI such as a worksheet, result grid, dashboard, or autocomplete | Spend more time on browser behavior, state, networking, and rendering than cloud boxes. |
| Project / behavioral | Deep project walkthrough, collaboration, tradeoffs, mistakes | Choose one frontend project where you can explain design, rollout, metrics, and failures. |
Treat your recruiter instructions as the source of truth. Some loops lean React-heavy; others include a general software engineering coding round.
Use these as practice prompts, not a guaranteed question bank. They cover the recurring shape: interactive grids, JavaScript utilities, React rendering, data-heavy UI, and frontend architecture.
| Snowflake question or task | What to practice |
|---|---|
| Build a checkerboard where the board size is configurable and each square renders the correct alternating color. | 2D rendering, derived cells, props, CSS grid, React state |
| Extend the checkerboard with selectable cells, keyboard navigation, and reset behavior. | Focus state, arrow keys, stable coordinates, accessibility |
| Build a robot-grid game where a robot moves within boundaries and cannot leave the board. | Event handling, grid state, boundary checks, testable move logic |
| Add randomized target cells, a score counter, and collision detection to the robot grid. | Derived state, random placement, win conditions, reset logic |
| Validate a Tic Tac Toe or Sudoku board and explain invalid states. | Game-state invariants, row/column scans, sets, edge cases |
| Find the minimum-cost path from one node or cell to another in a graph or grid. | BFS, Dijkstra-style thinking, dynamic programming, complexity |
Explain useMemo and useCallback, then decide where memoization helps in a table or editor UI. | React render behavior, reference identity, profiling judgment |
| Implement an event emitter with subscribe, unsubscribe, emit, and one-time listeners. | Map, Set, cleanup, listener mutation during emit |
| Implement debounce or throttle and explain where it belongs in a SQL editor or object search. | Timers, closures, cancellation, search pacing |
| Build a data table that supports sorting, pagination, loading, empty, and error states. | Large result rendering, state derivation, URL state, accessibility |
| Design a query-result viewer that can handle thousands of rows without freezing the page. | Virtualization, pagination, column sizing, copy behavior, query cancellation |
| Build an autocomplete for SQL keywords, table names, and column names. | Request ordering, ranking, permissions, keyboard combobox behavior |
| Implement undo/redo for a small calculator or editor command history. | Command pattern, reversible state, stacks, redo invalidation |
Recreate a subset of JSON.stringify or deep clone for common JavaScript values. | Recursion, type checks, arrays vs objects, unsupported values |
| Design a Snowsight-style worksheet with code editor, query execution, result panel, saved tabs, and query history. | Frontend system design, state ownership, async query lifecycle |
| Design a dashboard builder where each tile runs its own query and shares filters with other tiles. | Multi-request state, cache, chart rendering, partial failure |
| Explain one frontend project you owned, including constraints, tradeoffs, and what you would change now. | Project depth, communication, ownership |
The checkerboard prompt looks simple, but it tests whether you separate data from rendering. Start by naming the state:
One clean helper:
type Cell = {id: string;row: number;column: number;tone: 'light' | 'dark';};function createBoard(size: number): Array<Cell> {return Array.from({ length: size * size }, (_, index) => {// Convert the flat array index back into board coordinates.const row = Math.floor(index / size);const column = index % size;return {id: `${row}-${column}`,row,column,tone: (row + column) % 2 === 0 ? 'light' : 'dark',};});}
Then explain follow-ups:
createBoard(size) only when board creation or rendering becomes measurable; do not add memoization as decoration.For a robot grid, use the same coordinate model. The move function should be independent of React so it can be tested quickly:
type Position = {row: number;column: number;};function move(position: Position,direction: 'up' | 'down' | 'left' | 'right',size: number,): Position {const next = {up: { row: position.row - 1, column: position.column },down: { row: position.row + 1, column: position.column },left: { row: position.row, column: position.column - 1 },right: { row: position.row, column: position.column + 1 },}[direction];return {// Clamp movement so the robot stays inside the board.row: Math.max(0, Math.min(size - 1, next.row)),column: Math.max(0, Math.min(size - 1, next.column)),};}
This is the fastest path to a working answer: pure logic first, UI rendering second, follow-ups third.
React hook questions at Snowflake usually matter because data-tool UIs can rerender large trees: editors, result panes, side panels, schema browsers, and tables. Avoid memorized definitions. Explain what problem each hook solves.
| Hook | Useful answer | Bad interview habit |
|---|---|---|
useMemo | Cache an expensive derived value between renders when dependencies are stable. | Wrapping every computed value without measuring cost. |
useCallback | Keep a function reference stable when a memoized child or subscription depends on identity. | Using it for every event handler even when no child benefits. |
useRef | Store mutable values that should not trigger rerenders, such as latest request ID, DOM node, or timer ID. | Using refs to bypass React state for visible UI. |
useEffect | Synchronize with systems outside render: network subscriptions, timers, editor instances, browser events. | Fetching without cleanup or ignoring stale responses. |
For a result table, say this:
useMemo for derived rows only if filtering, sorting, or grouping is expensive enough to matter.useCallback when row actions are passed into memoized row components.Practice this answer with Data Table and Users Database. The useful skill is deciding where state lives and what is derived, not reciting hook definitions.
An event emitter maps well to Snowflake-style frontends because editor events, query status updates, workspace tabs, and panels all need subscription cleanup.
Start with the API:
type Listener<T = unknown> = (payload: T) => void;class EventEmitter {private listeners = new Map<string, Set<Listener>>();on(eventName: string, listener: Listener) {if (!this.listeners.has(eventName)) {this.listeners.set(eventName, new Set());}this.listeners.get(eventName)!.add(listener);return () => this.off(eventName, listener);}off(eventName: string, listener: Listener) {const listeners = this.listeners.get(eventName);if (listeners == null) {return;}listeners.delete(listener);if (listeners.size === 0) {this.listeners.delete(eventName);}}emit(eventName: string, payload?: unknown) {const listeners = this.listeners.get(eventName);if (listeners == null) {return;}// Snapshot listeners so unsubscribe calls during emit do not skip callbacks.for (const listener of Array.from(listeners)) {listener(payload);}}once(eventName: string, listener: Listener) {const unsubscribe = this.on(eventName, (payload) => {unsubscribe();listener(payload);});return unsubscribe;}}
Explain the edge cases after the baseline works:
emitonFor a frontend round, Map<string, Set<Listener>> is a good default. It gives constant-time deletion, avoids accidental duplicate listeners, and keeps cleanup easy to explain.
Snowflake product context makes table questions more important than they look. Snowsight dashboards and worksheets display query results, charts, and tables. A naive table is fine for 50 rows; it starts to break when the user sorts, filters, resizes columns, copies cells, runs a new query, or changes role permissions.
Start with a clear model:
type QueryResultState = {queryId: string;status: 'idle' | 'running' | 'success' | 'error' | 'canceled';columns: Array<{ id: string; label: string; type: string }>;rows: Array<Record<string, string | number | boolean | null>>;sort: { columnId: string; direction: 'asc' | 'desc' } | null;page: number;errorMessage?: string;};
Then cover:
Practice Data Table and How to handle large datasets in front-end applications, then adapt the answer to query results instead of generic users.
A Snowflake frontend system design round should spend most of its time on the browser contract. A good worksheet design includes a code editor, run controls, context selector, query history, result panel, saved tabs, schema browser, and an optional AI assistant panel.
Clarify scope first:
Then organize the answer:
| Design area | What to cover |
|---|---|
| Editor | Monaco-style editor, syntax highlighting, keyboard shortcuts, autocomplete providers |
| Query lifecycle | Run, cancel, rerun, timeout, syntax error, permission error, and result pagination |
| State ownership | Local draft, saved worksheet, active tab, warehouse/role context, query result cache |
| Result rendering | Pagination, row virtualization, column resizing, sticky headers, copy cell, chart handoff |
| Autocomplete | SQL keywords, functions, table names, column names, permission-aware catalog search |
| AI panel | Streaming suggestions, accepting/rejecting edits, cancellation, prompt context, audit trail |
| Performance | Lazy-load editor and chart bundles, avoid rendering all results, isolate heavy panels |
| Reliability | Ignore stale responses, recover drafts, retry transient failures, keep failed panels contained |
| Accessibility | Keyboard navigation, focus recovery, command labels, screen-reader-friendly status updates |
The strongest answers connect product behavior to implementation. For example, if the user changes role or warehouse, cached schema suggestions may no longer be valid. If a query is canceled, the result panel should show the canceled state for that query, not a generic error. If a large result set comes back, the app should render the first page quickly and avoid locking the main thread.
Useful GreatFrontEnd practice:
Snowflake prep should cover both frontend utilities and algorithmic grid problems.
| Topic | Practice questions |
|---|---|
| Arrays and strings | Flatten, deep clone, JSON.stringify, find duplicates, group records, merge sorted arrays |
| Timers and async | Debounce, throttle, promise utilities, stale response guards, retry with backoff |
| Events | Event emitter, pub/sub cleanup, keyboard handlers, listener mutation during emit |
| UI games | Checkerboard, robot grid, Tic Tac Toe, Sudoku validation, memory game |
| Graphs and grids | BFS, DFS, shortest path, minimum-cost path, visited-state tracking |
| React | Hooks, memoization, controlled inputs, derived state, focus management, rendering large lists |
| System design | Worksheet, autocomplete, result grid, dashboard, AI assistant panel |
Do not treat DSA as a separate universe. Many Snowflake-friendly coding prompts are grid UI prompts that become graph problems through follow-ups.
Use official Snowflake material to make system design answers concrete:
Use this as a Snowflake-specific checklist. The order matters less than the coverage: JavaScript, grid UI, data rendering, system design, and project depth.
| Prep area | What to do | Snowflake-specific angle |
|---|---|---|
| JavaScript fundamentals | Implement event emitter, debounce, throttle, deep clone, JSON.stringify, promise utilities, and undo/redo. | These show language control without framework help. |
| React UI coding | Build checkerboard, robot grid, Tic Tac Toe, typeahead, tabs, and editable table in timed 30-45 minute sessions. | Grid prompts map well to Snowflake's UI-coding style. |
| Data-heavy UI | Build data table, virtualized result viewer, dashboard tile layout, and schema browser. | Snowsight work depends on rendering, searching, and navigating large data views. |
| Algorithms | Practice BFS/DFS, shortest path, DP on grids, Sudoku validation, and graph traversal. | Some frontend prompts deepen into graph or path problems. |
| Frontend system design | Design worksheet, autocomplete, query-result grid, dashboard builder, and AI side panel. | Explain editor state, query lifecycle, cancellation, permissions, virtualization, and progressive results. |
| Behavioral and project depth | Prepare one project deep dive and 6-8 stories across ownership, collaboration, mistakes, mentoring, and tradeoffs. | Choose stories involving complex UI, performance, data visualization, platform tooling, or editor work. |
| Mock loop | Run one React mock, one JavaScript utility mock, one grid/DSA mock, one system design mock, and one project deep dive. | Fix weak answers after each mock instead of adding random questions. |
If you have only 72 hours, prioritize checkerboard or robot grid, event emitter, debounce, data table, one graph shortest-path problem, worksheet system design, and your best project story.
Snowflake frontend prep should end with one clear story: "I can build the UI, explain the JavaScript, and reason about data-tool behavior in the browser." That means the best practice set is not 100 random React questions. It is a smaller set of Snowflake-shaped drills: interactive grids, React hooks, event emitter, debounce, result tables, autocomplete, graph traversal, and a Snowsight worksheet design.

Discord frontend interview questions usually test whether you can build and explain realtime product UI: chat, message lists, editable components, async events, large-list rendering, and JavaScript primitives that keep a client responsive. Prepare for React, TypeScript, browser fundamentals, frontend system design, and behavioral rounds about collaboration and product judgment.
For the company-guide view, use the Discord Front End Interview Guide alongside this article.
Use each question as a working session: solve the baseline prompt, then explain what would change for larger data, unreliable connections, accessibility requirements, slow devices, and product follow-ups.
Discord is a realtime communication product, so frontend interviews do not stop at "can you render a component?" A useful Discord client has to handle fast-changing events, long chat histories, thousands of members and channels, typing indicators, presence, reactions, attachments, markdown, voice/video state, unreliable connections, and heavy user-generated content.
| Area | What to practice | Why it matters at Discord |
|---|---|---|
| React implementation | Chat UI, editable cells, spreadsheet grids, message actions, mention pickers, virtualized lists | These map to message views, channel lists, member lists, modals, and internal tooling. |
| JavaScript | Event emitter, debounce, throttle, DOM traversal, async events, timers, stale updates | Realtime clients depend on event routing, cleanup, and input pacing. |
| Realtime UI | Optimistic messages, retries, typing indicators, reconnect behavior, duplicate event handling | A chat client must feel fast while still correcting itself when the network disagrees. |
| Data modeling | Messages, channels, users, cell formulas, derived values, normalized state | The interview often deepens through follow-ups that punish copied or duplicated state. |
| Frontend system design | Discord-style chat, messaging systems, presence, autocomplete, server recommendations | The strongest answers connect UI behavior to API contracts and transport choices. |
| Behavioral | Ownership, ambiguity, conflict, feedback, product usage, cross-functional work | Discord's loop includes values and cross-functional signal, not only coding. |
The best preparation is to build Discord-shaped interfaces, then explain how they behave when data grows, events arrive out of order, or the user loses connection.
The exact process changes by team and level, but prepare for this shape:
| Stage | What to expect | Prep note |
|---|---|---|
| Recruiter screen | Role fit, timeline, compensation, location, and interview logistics | Ask whether the technical round is React, JavaScript, DSA, or fullstack. |
| Hiring manager screen | Background, project depth, Discord interest, and team alignment | Prepare a concise story about why Discord and what product areas you use. |
| Technical screen | One practical coding exercise, often in your own editor or a live UI | Build a working baseline before optimizing or abstracting. |
| Final interview loop | Coding, architecture, project discussion, values, and cross-function | Practice narrating tradeoffs, not only writing code. |
| Senior/project deep dive | A project retrospective with architecture, alternatives, and impact | Pick one project where you owned meaningful frontend decisions. |
Discord's own interview preparation guide says technical interviews are based on real work and can include coding, architecture, values, attitude, and specialty sessions. That is the right way to calibrate your prep: practice building and explaining product features, not memorizing trivia.
Treat your recruiter's instructions as the source of truth. Your loop may be frontend-only, backend-aware, or broader architecture-heavy depending on the role.
Use these as practice prompts, not a guaranteed question bank. They cover the recurring Discord-style patterns: realtime UI, chat state, editable components, JavaScript primitives, and frontend system design.
| Discord question or task | What to practice |
|---|---|
| Build a Discord-like chat interface with a message composer, message list, and basic message actions. | React state, list rendering, controlled input, optimistic updates |
| Extend a chat UI so users can edit, delete, retry, and display message-send status. | Message identity, derived status, rollback behavior, error states |
| Add typing indicators and reconnect behavior to a chat view. | Timers, event expiry, WebSocket lifecycle, stale event cleanup |
| Build an editable React cell like a spreadsheet cell. | Display/edit mode, focus management, keyboard behavior, controlled inputs |
| Build a spreadsheet-style grid where users can edit cells and enter simple formulas. | Cell data model, dependency tracking, recalculation, circular references |
| Implement a debounce utility and explain where it would be useful in Discord. | Closures, timers, cancellation, search and typing-indicator pacing |
| Implement an event emitter with subscribe, unsubscribe, emit, and once behavior. | Listener storage, cleanup, re-entrancy, event payloads |
| Write a function that finds elements by class name without using the browser's native helper. | DOM traversal, recursion or iteration, matching logic |
| Build a simple socket-based chat service or messaging layer. | Message delivery, connection lifecycle, fan-out, ordering |
| Design a user messaging system that supports sending, receiving, editing, and displaying messages reliably. | Client-server contracts, WebSocket events, idempotency, retry behavior |
| Solve a word-search, substring, or trie-style lookup problem. | Strings, prefix search, tries, complexity analysis |
| Design a Discord-like chat client from the frontend perspective. | Data model, transport events, normalized state, rendering, offline behavior |
| Design realtime recommendations for users joining new servers or communities. | Product systems, ranking signals, frontend data needs, empty states |
| Walk through a project you led and explain the technical tradeoffs you made. | Project depth, ownership, alternatives, results |
| Explain why you want to work at Discord and what part of the product interests you. | Product usage, motivation, user empathy |
| Describe a time a project failed, requirements changed, or feedback forced you to adjust your technical direction. | Reflection, collaboration, judgment |
Notice the repeated theme: practical UI plus event-driven state. Even a simple utility question can lead back to Discord's product. Debounce connects to search and typing indicators. Event emitters connect to gateway events. Editable grids connect to internal tools and data-heavy UI. Chat prompts connect to the core product.
Start with a small data model before writing components:
type MessageStatus = 'sending' | 'sent' | 'failed';type Message = {id: string;channelId: string;authorId: string;content: string;createdAt: number;editedAt?: number;status: MessageStatus;};
Use stable message IDs, not array indexes. Keep the input draft separate from the message list. Derive visible state from messages rather than copying the same information into several local states.
A good baseline includes:
Then discuss follow-ups:
Practice the base implementation with Data Table for stable row identity and Autocomplete for async input behavior, then adapt those habits to chat.
The editable-cell prompt looks small, but it tests whether you can separate UI mode, input state, saved state, focus, and keyboard behavior.
Start with one cell:
One possible component contract:
type EditableCellProps = {id: string;value: string;onCommit: (id: string, nextValue: string) => void;onNavigate?: (id: string,direction: 'up' | 'down' | 'left' | 'right',) => void;};
Keep transient draft text inside the cell while editing. Keep committed cell values in the parent grid. That gives the parent one source of truth and still lets each cell manage local focus and selection behavior.
For a spreadsheet grid, explain the deeper model:
type Cell = {id: string; // "A1", "B2", etc.rawValue: string; // typed text, including formulascomputedValue: string | number | null;error?: 'invalid-formula' | 'circular-reference';};
Important follow-ups:
A1 and B2 into dependenciesDo not overbuild the parser in the first 20 minutes. Ship editable cells first, then add formulas in layers.
An event emitter is a small problem with many useful edge cases. It maps well to Discord because realtime clients receive events from one transport and distribute updates to many pieces of UI.
Start with the API:
type Listener<T = unknown> = (payload: T) => void;class EventEmitter {private listeners = new Map<string, Set<Listener>>();on(eventName: string, listener: Listener) {if (!this.listeners.has(eventName)) {this.listeners.set(eventName, new Set());}this.listeners.get(eventName)!.add(listener);return () => this.off(eventName, listener);}off(eventName: string, listener: Listener) {this.listeners.get(eventName)?.delete(listener);}emit(eventName: string, payload?: unknown) {const listeners = this.listeners.get(eventName);if (listeners == null) {return;}for (const listener of Array.from(listeners)) {listener(payload);}}once(eventName: string, listener: Listener) {const unsubscribe = this.on(eventName, (payload) => {unsubscribe();listener(payload);});return unsubscribe;}}
Then discuss edge cases:
emit is running?off clean up empty event sets?on return an unsubscribe function?For interview code, Map<string, Set<Listener>> is a clean default. It makes listener removal easier than an array and prevents accidental duplicates.
Debounce delays a function until calls stop for a given amount of time. In Discord-shaped UI, it appears in search, mention pickers, typing indicators, resize handlers, and scroll-linked work.
Implement the baseline:
function debounce(fn, delay) {let timerId;return function debounced(...args) {clearTimeout(timerId);timerId = setTimeout(() => {fn.apply(this, args);}, delay);};}
Then explain product usage:
Mention the limits too. Do not debounce the actual input state update, because typing should feel immediate. Debounce the side effect: network request, analytics call, or expensive calculation.
If asked for a fuller implementation, add cancel, flush, leading-edge execution, and return-value behavior. Name those as follow-ups rather than trying to cram every feature into the first version.
For a frontend system design round, do not start by drawing components. Start by clarifying scope:
Then structure the answer around the browser contract. Discord's engineering post on reducing WebSocket traffic by 40% is useful context here because it explains the gateway, payloads such as MESSAGE_CREATE and TYPING_START, passive sessions, and why client bandwidth matters for realtime UI.
| Design area | What to cover |
|---|---|
| Data model | Messages, users, channels, servers, members, reactions, typing state, presence, drafts |
| Transport | WebSocket events for realtime updates, HTTP for history, reconnect and resume behavior |
| State management | Normalized entities, per-channel message IDs, local drafts, optimistic sends, subscription cleanup |
| Rendering | Virtualized message list, scroll anchoring, dynamic row heights, lazy embeds, markdown rendering |
| Reliability | Retry failed sends, dedupe duplicate events, ignore stale events, handle reconnect gaps |
| Performance | Avoid global rerenders, memoize expensive message rows, split heavy features, clean up listeners |
| Accessibility | Keyboard navigation, focus recovery, readable controls, announcement of new messages when needed |
| Testing | Message send, retry, edit, delete, duplicate event, reconnect, scroll preservation |
One useful state shape:
type ChatState = {messagesById: Record<string, Message>;messageIdsByChannelId: Record<string, Array<string>>;draftsByChannelId: Record<string, string>;typingUserIdsByChannelId: Record<string, Array<string>>;};
From there, describe event handling:
MESSAGE_CREATE: insert message if it is not already presentMESSAGE_UPDATE: patch the existing message by IDMESSAGE_DELETE: remove or tombstone the messageTYPING_START: show typing state with an expiry timerPRESENCE_UPDATE: update visible presence without rerendering every unrelated messageRECONNECT: resume from the last known event sequence when possible; otherwise refetch the active channelThe key tradeoff: the UI should feel instant, but the server remains the source of truth for message identity, ordering, permissions, moderation, and delivery state. For performance follow-ups, Discord's post on maintaining performance while adding features is a good model for discussing code splitting, lazy loading, retrying failed chunks, and keeping a large client fast as features accumulate.
Read these after building the baseline chat UI. They give you concrete language for system design, performance, accessibility, and product-specific follow-ups.
| Official Discord resource | What to use it for |
|---|---|
| How to prepare for your Discord interview | Round structure, technical interview expectations, architecture interviews, values, and cross-functional conversations. |
| How Discord Reduced WebSocket Traffic by 40% | Gateway events, compressed payloads, passive sessions, bandwidth tradeoffs, and realtime client design. |
| How Discord Maintains Performance While Adding Features | Code splitting, lazy loading, retry behavior, bundle size, route-level chunks, and frontend performance tradeoffs. |
| How Discord Implemented App-Wide Keyboard Navigation | Accessibility, focus management, keyboard navigation, component-system constraints, and custom focus rings. |
| How Discord achieves native iOS performance with React Native | React Native performance, store dispatch costs, message parsing, virtualization, and mobile client tradeoffs. |
| How Discord Handles Two and Half Million Concurrent Voice Users using WebRTC | Voice/video architecture, WebRTC constraints, browser vs native client behavior, and media performance. |
Review React through Discord-style examples, not isolated definitions.
| Topic | Discord-shaped way to practice |
|---|---|
useState and useRef | Manage a draft message, input focus, pending scroll action, and latest request ID. |
useEffect | Subscribe to WebSocket events and clean up listeners when the channel changes. |
useMemo | Derive visible message IDs from normalized state when the transform is expensive enough. |
useCallback | Stabilize callbacks only when child memoization or subscription identity actually needs it. |
| Controlled inputs | Build message composer, search box, and editable spreadsheet cell. |
| Component composition | Split message row, composer, channel header, reaction picker, and typing indicator sensibly. |
| Context | Use it for stable app-level dependencies, not every message update. |
| Error boundaries | Keep one broken embed or markdown block from breaking the whole chat view. |
| Performance profiling | Find unnecessary rerenders in message rows, member lists, or virtualized lists. |
| Accessibility | Make modals, menus, keyboard navigation, and message actions reachable without a mouse. |
Avoid generic answers like "use memoization for performance." Explain what rerenders, why it matters, and which optimization matches the bottleneck.
Discord frontend prep should include JavaScript fundamentals because many realtime UI bugs come from closures, timers, async work, and event cleanup.
Practice:
setTimeout, setInterval, and cleanupTie each topic to a product bug. For example, a stale closure can send a message to the previously selected channel. A missing cleanup can leave an old channel subscription active. A naive DOM traversal can miss nested elements. A search request that returns late can overwrite newer results.
Useful GreatFrontEnd practice:
Do not treat the behavioral round as a formality. Discord interviews include signals around values, attitude, product usage, collaboration, and how you respond to feedback.
Prepare stories for:
For each story, prepare the user problem, your role, the constraints, alternatives considered, the decision, the result, and what you would change now. Specific stories beat polished generalities.
Also use the product before the interview. Create or manage a server, try roles and permissions, use channels, threads, voice, screen share, reactions, search, notifications, and moderation settings. Product familiarity makes system design and behavioral answers much more concrete.
Use this as a Discord-specific checklist. The exact order can change based on your timeline, but the coverage should stay the same: chat UI, spreadsheet-style components, realtime primitives, frontend system design, and behavioral depth.
| Prep area | What to do | Discord-specific angle |
|---|---|---|
| Chat UI implementation | Build a React and TypeScript chat app with composer, message list, edit, delete, retry, typing state, and older-message loading. | Practice optimistic sends, duplicate event reconciliation, scroll preservation, and channel switching. |
| Spreadsheet-style coding | Build editable cells, keyboard navigation, formula references, dependency recalculation, and circular-reference handling. | This tests state modeling and follow-up resilience, not only UI rendering. |
| JavaScript primitives | Implement debounce, throttle, event emitter, DOM traversal, and a small rate limiter from scratch. | Connect each primitive to search, typing indicators, gateway events, and message-send pacing. |
| Realtime system design | Design Discord chat, typing indicators, presence, message history, and reconnect behavior from the frontend perspective. | Cover WebSocket events, HTTP history, normalized state, optimistic UI, offline behavior, and cleanup. |
| Performance practice | Add virtualization to message/member/channel lists and profile unnecessary rerenders. | Discord-like UIs are list-heavy and can become slow without stable identity and careful subscriptions. |
| Behavioral and product prep | Prepare project stories and use Discord deeply enough to discuss specific flows. | Values and cross-functional rounds reward evidence, not generic interest in communication products. |
| Mock loop | Run one React mock, one JavaScript utility mock, one system design mock, and one project deep dive. | Fix weak answers after each mock instead of collecting more random questions. |
Prepare for Discord by building the interfaces Discord actually depends on: chat, editable grids, realtime event handlers, long lists, search, and presence. Memorizing React definitions is not enough if your code falls apart when messages arrive out of order or the user changes channels mid-request.
In coding rounds, ship a working baseline first. In system design, explain the client-server contract and the failure modes. In behavioral rounds, bring concrete product usage and project stories with real tradeoffs.
If you can build a chat UI, reason through editable grid state, implement core JavaScript utilities, and explain realtime frontend architecture clearly, you are preparing for the right interview shape.

PayPal frontend interview questions usually test JavaScript, React, DSA, and payment-system reasoning in the same loop. Prepare for practical UI coding, React internals, browser architecture, and checkout-specific design topics such as security, retries, idempotency, iframes, currency handling, and accessible payment flows.
For the company-guide view, use the PayPal Front End Interview Guide alongside this article.
Use each question as a working session: solve the baseline prompt, then explain what changes for payment reliability, accessibility, security, multi-currency handling, slow networks, and backend ownership.
PayPal is a payments company, so frontend interviews do not stop at rendering a button. A checkout UI has to handle money, risk, privacy, failed networks, user trust, third-party merchant pages, and strict accessibility expectations. That product context explains the mix of React, JavaScript utilities, DSA, system design, and backend-aware architecture.
| Area | What to practice | Why it matters at PayPal |
|---|---|---|
| React implementation | Cart UI, file explorer, typeahead, form validation, currency converter, checkout widgets | These map to checkout, merchant dashboards, wallet flows, and SDK examples. |
| JavaScript | Async classes, reduce, flatten, deep copy, closures, promises, event loop, debounce, throttle | These show whether you can handle utility code and async data flow clearly. |
| DSA | Strings, arrays, stacks, DP, graphs, binary search, LRU cache | PayPal coding screens can still include LeetCode-medium style problems. |
| Browser fundamentals | DOM vs BOM, cookies, security, CDN, loading, accessibility, performance | Checkout and dashboard work requires browser-to-backend reasoning. |
| Frontend system design | Checkout SDK, payment gateway, transaction dashboard, real-time fraud queue | Payments UI sits across frontend, API, ledger, risk, and operations systems. |
| Behavioral | Ownership, conflict, mentoring, decision-making, project depth | Senior and staff loops include manager or bar-raiser discussions. |
PayPal's official careers guidance says recruiters usually reach out by phone, interviews are virtual on Microsoft Teams, and applicants should study the job description, company values, and Leadership Principles. It also points applicants to a prep video series.
Expect a process shaped roughly like this:
| Stage | What to expect | Prep note |
|---|---|---|
| Recruiter screen | Background, role fit, location, timeline, interview format | Ask whether the first technical round is HackerRank, Karat, DSA, React, or role-specialization. |
| Online assessment | HackerRank-style React, JavaScript, and DSA tasks | Be ready for 60-150 minutes depending on the assessment. |
| Technical coding | DSA, JavaScript utilities, React machine coding, code review | Use JavaScript or TypeScript unless recruiter says any language is acceptable. |
| Role specialization | React internals, hooks, state, fetch, tests, frontend architecture | Expect deeper follow-ups for SDE-2, senior, and staff roles. |
| System design | Payment gateway, checkout flow, web architecture from browser to backend | Explain both client behavior and backend contracts. |
| Behavioral / bar raiser | Project depth, conflict, mentoring, tradeoffs, ownership | Prepare varied STAR stories, especially around customer impact and reliability. |
Use these as practice prompts, not a guaranteed question bank. For each one, timebox a working baseline first, then talk through tradeoffs, edge cases, accessibility, performance, and tests.
| PayPal question or task to practice | What to practice |
|---|---|
Build a small async data wrapper class with get and create-style methods. It should return stored values, reject missing reads, and reject duplicate writes. | Async JavaScript, classes, promise sequencing, error handling |
| Build a React cart where users can change quantities, remove items, and see totals update immediately. | Cart state, derived totals, immutable updates, testable UI |
| Solve a dynamic-programming triangle path problem, implement a stack with constant-time minimum lookup, and explain topological sorting. | Dynamic programming, stack design, graph ordering |
| Design a payment gateway and explain the transaction flow, consistency model, ledger behavior, retries, and failure handling. | PayPal orders, payment sessions, idempotency, ledger, webhooks, retries |
| Explain React reconciliation and sketch a simplified algorithm for comparing an old UI tree with a new one. | React rendering internals, tree comparison, keyed lists, rerender causes |
| Build a React currency converter with controlled inputs and recalculated output. | Controlled inputs, derived state, Intl.NumberFormat, precision, async rates |
| Given a string, remove the smallest possible contiguous section so the remaining characters satisfy a uniqueness constraint. | Sliding window, character counts, edge cases |
| Write a deep-copy function, then adapt it to apply one extra transformation to arrays during copying. | Recursion, arrays vs objects, reference safety, cycles if asked |
| Complete missing React component logic, then implement an LRU Cache. | Component state, DSA data structures, Map plus linked-list reasoning |
| Walk through a web application from DNS and CDN to browser cookies, security, backend storage, cache, and real-time communication choices. | End-to-end web architecture, network basics, API design, storage choices |
| Build a React form with validation, visible error states, and disabled submission while invalid. | Forms, validation state, error messages, disabled submission, accessibility |
| Build a simple page in a frontend framework and pair it with a small object-oriented backend model. | Full-stack UI basics, component composition, simple backend model |
| Solve a paint-fill style grid traversal problem. | Grid traversal, DFS/BFS, visited checks |
| Explain ES6 features through examples from your own project work. | Project-based JavaScript, modules, destructuring, promises, classes, iterators |
Explain why a team might choose React, describe page performance improvements, then implement Array.prototype.reduce behavior in vanilla JavaScript. | React tradeoffs, rendering performance, array methods, polyfills |
| Build a typeahead that filters a list as the user types and includes a clear-input control. | Typeahead logic, clear control, accessible combobox basics, browser terms |
| Find all anagrams of a pattern inside a string, then implement array flattening with configurable depth. | Sliding window, recursive or iterative flatten, edge cases |
| Build a nested file explorer in React with expand/collapse and basic create, rename, and delete actions. | Recursive data, local edit state, immutable tree updates |
| Build a small shopping app with routes, navigation, cart add/remove behavior, duplicate prevention, total calculation, and test-friendly markup. | Machine coding, routing, shared state without Redux, test-driven details |
| For a staff-level frontend role, answer JavaScript, TypeScript, frontend architecture, React, component library, system design, and behavioral questions. | Staff-level frontend architecture, LLD, HLD, component APIs, leadership |
| Build a React task using hooks, state, data fetching, error handling, and a small test strategy; then discuss REST APIs, pagination, caching, auth, and indexing. | Full-stack frontend specialization, API-backed React, backend awareness |
| Solve short array-manipulation tasks and simple calculation problems under time pressure. | Arrays, loops, basic transformation, correctness under time |
The cart prompt is common because it tests a payment-adjacent workflow without requiring a real payment API. Start with the smallest data model that can survive follow-ups:
type CartItem = {id: string;name: string;priceCents: number;quantity: number;};
Use item IDs as identity. Derive subtotal, itemCount, and disabled states from the cart array instead of duplicating them in separate state variables. That makes quantity changes, removal, and duplicate prevention easier to reason about.
A complete answer covers:
Intl.NumberFormat. PayPal's currency code reference is useful here because some supported currencies do not allow decimal amounts.Practice this with Data Table for tabular rendering and Contact Form for validation habits, then adapt the state model to a cart.
Fetcher classThe Fetcher prompt checks whether you can wrap an async dependency without losing error semantics. Do not jump straight to try/catch; first name the contract:
get(id) resolves with the stored object when it existsget(id) rejects or throws when the ID does not existpost(id, value) creates a value for an unused IDpost(id, value) rejects or throws when the ID already existsDB.read and DB.create are asyncOne possible shape:
class Fetcher {constructor(db) {this.db = db;}async get(id) {const value = await this.db.read(id);if (value == null) {throw new Error('ID not found');}return value;}async post(id, value) {const existing = await this.db.read(id);if (existing != null) {throw new Error('ID already exists');}return this.db.create(id, value);}}
Then discuss race conditions. If two post(7, value) calls run at the same time, both can read "empty" before either creates. In an interview, say that the real fix belongs in the database or API layer through a uniqueness constraint, transaction, or atomic create. The frontend wrapper can expose errors clearly, but it cannot guarantee cross-client uniqueness by itself.
PayPal uses country pickers, currency selectors, merchant search, transaction filters, and support flows where typeahead behavior matters. A baseline implementation is not enough if it overwrites newer results with older responses.
Mention these requirements before coding:
AbortControllerFor system design depth, practice Autocomplete. For UI implementation speed, practice Users Database.
React internals questions are easier when you connect the concept to a bug or design decision. Keep the answer practical:
If asked to pseudocode diffing, use a simplified tree compare:
function diff(previousNode, nextNode) {if (previousNode == null) return { type: 'insert', node: nextNode };if (nextNode == null) return { type: 'remove', node: previousNode };if (previousNode.type !== nextNode.type) {return { type: 'replace', node: nextNode };}return {type: 'update',props: diffProps(previousNode.props, nextNode.props),children: diffChildren(previousNode.children, nextNode.children),};}
Then add the caveat: real React reconciliation is much more complex, but the interview wants to see identity, tree comparison, and keys.
This is the round where generic frontend prep runs out. A payment gateway design asks you to connect browser behavior, SDK boundaries, server APIs, risk checks, and ledger systems.
Start from the user action:
Payments need extra care:
PayPal's own SDK and integration materials are useful background here. Review the JavaScript SDK, React SDK v6, hosted Card Fields model, Orders API, and sandboxed iframe integration pattern before a system design round. Keep the concepts separate: PayPal wallet flows use a PayPal payment session, Card Fields keep raw card data inside PayPal-hosted iframes, and the sandboxed iframe guide shows an advanced wrapper pattern where the merchant page and isolated payment frame communicate with postMessage. For duplicate-submit and retry discussions, mention PayPal's PayPal-Request-Id idempotency header.
PayPal interview prep clusters around a few repeatable patterns.
| Topic | Practice questions |
|---|---|
| Arrays and strings | Find all anagrams, longest substring without repeating characters, remove minimum substring for unique characters |
| Stacks and caches | Min Stack, LRU Cache |
| DP and graphs | Triangle DP, Paint Bucket Fill, topological sort, grid BFS |
| JavaScript utilities | reduce, flatten with depth, deep copy, debounce, throttle |
| Async JavaScript | Fetcher class, fetch with loading/error states, retries, stale responses |
| React machine coding | Cart, shopping app, file explorer, form validation, typeahead, currency converter |
| Browser and web | DOM vs BOM, cookies, CDN, DNS, WebSockets, long polling, accessibility |
Useful GreatFrontEnd practice:
Use PayPal's own docs to make payment-system answers concrete instead of generic:
PayPal-Request-Id, retries, duplicate prevention, and unclear response handling.postMessage.Use this as a PayPal-specific checklist. The exact order can change based on your timeline, but the coverage should stay the same: JavaScript, React machine coding, payments architecture, and behavioral depth.
| Prep area | What to do | PayPal-specific angle |
|---|---|---|
| JavaScript and DSA | Solve Min Stack, LRU Cache, flatten, reduce, deep clone, anagrams, one sliding-window problem, and one DP problem. | Keep utility implementation and LeetCode-medium style coding both warm. |
| React machine coding | Build cart, file explorer, form validation, typeahead, shopping app, and currency converter in timed 45-60 minute sessions. | Narrate state ownership, derived totals, validation, accessibility, loading states, and test selectors. |
| Payments architecture | Design checkout SDK, payment gateway, merchant transaction table, and fraud-review queue. | Include PayPal orders, server-side create/capture, idempotency, Card Fields, iframe isolation, webhooks, and reconciliation. |
| Browser and web architecture | Review DNS, CDN, cookies, cache, WebSockets, long polling, security, and storage choices. | Explain how a checkout or merchant dashboard moves from browser interaction to backend services. |
| Behavioral and project depth | Prepare one deep frontend project story and 6-8 STAR examples across conflict, ownership, reliability, mentoring, and tradeoffs. | Choose examples involving risk, customer trust, accessibility, performance, or security-sensitive UI. |
| Mock loop | Run one DSA mock, one React mock, one system design mock, and one behavioral project deep dive. | After each mock, fix the weakest answer rather than adding more random questions. |
If you have only 72 hours, prioritize cart UI, typeahead, reduce, flatten, LRU Cache, one payment gateway design, and your best project story.
PayPal's careers guidance asks applicants to prepare detailed examples and vary stories across roles. For frontend engineers, choose stories that involve product risk, reliability, accessibility, security-sensitive UI, or cross-team execution.
Prepare stories for:
For each story, include the user problem, the technical constraint, the options considered, the decision, the result, and what you would do differently now.
PayPal frontend prep should end with one clear story: "I can build the UI, explain the JavaScript, and reason about what happens when money moves." That means the best practice set is not 100 random React questions. It is a smaller set of payment-shaped drills: cart, form validation, typeahead, currency converter, file explorer, Fetcher, flatten, deep clone, LRU Cache, and a checkout or payment-gateway system design.

Databricks frontend interview questions usually test data-heavy UI engineering: async search, API-backed components, request race conditions, large result tables, dashboards, collaboration, and system design. Your prep should also include algorithm and machine-coding rounds, so do not prepare only for React trivia.
The fastest way to prepare is to combine three sources of truth:
For the company-guide view, use the Databricks Front End Interview Guide alongside this article.
Databricks is not a generic consumer app company. The frontend work sits around notebooks, SQL editors, schema browsers, dashboards, workflows, model tools, governance UI, and AI-assisted data products. That changes the interview signal.
| Area | What to practice | Why it matters for Databricks |
|---|---|---|
| Async UI | Typeahead, cancellation, retries, stale response handling | Search and autocomplete appear in editors, catalogs, dashboards, and notebooks. |
| Data rendering | Tables, filters, pagination, virtualization, charts | Query results and dashboards can grow past what a simple component can handle. |
| JavaScript fundamentals | Closures, event loop, Set, Map, iterators, timers | JavaScript and data-structure follow-ups can appear in frontend loops. |
| System design | Collaborative editing, dashboards, autocomplete, real-time updates | Official frontend systems prep calls out client-server interfaces, API design, state, and sync. |
| Product implementation | Design-to-code constraints, empty states, loading states, error states | Databricks' official frontend code round expects a browser app that fetches and displays remote data. |
| Cross-functional judgment | Project depth, design collaboration, tradeoffs, customer impact | Official prep says cross-functional rounds dig into projects, decisions, and collaboration. |
The shape is closer to "build and explain a data product UI" than "recite React hooks." React can be useful, but Databricks' official prep says the frontend code round supports vanilla JS/DOM, React, Angular, Vue, and Svelte, so the core bar is web engineering, not one framework.
Databricks' public interview prep page describes seven hiring stages: identifying opportunities, applying online, connecting with Talent Acquisition, skill assessments, interviewing, reference checks, and decision/offer. It also says interviews usually run over Google Meet.
For front-end/full-stack software engineers, the April 2025 Databricks engineering prep PDF lists these interview types:
| Round | What Databricks says it evaluates | How to prepare |
|---|---|---|
| Front-End Code | Building a browser app that fetches and displays remote data, with async operations, efficient fetching, and UI state management | Practice typeahead, tables, search filters, loading/error/empty states, and request ordering bugs. |
| Front-End Systems | Client-server interfaces, API design, state management, data synchronization, and hands-on coding inside an open-ended design prompt | Design autocomplete, collaborative editing, dashboards, and large result panes, then implement one part. |
| Product Design | Turning Figma-like requirements into working implementation while discussing constraints with a designer | Explain layout, accessibility, state, edge cases, responsive behavior, and tradeoffs. |
| Front-End Infrastructure | Large refactors, migrations, testing infrastructure, build systems, performance, and code quality | Prepare examples from design systems, monorepos, migrations, CI, test reliability, and performance work. |
| Cross-Functional | Career path, motivation, major projects, decisions, collaboration, and leadership | Prepare project deep dives with technical detail and outcomes. |
Some loops also include algorithmic coding or backend/system-design rounds, especially for full-stack, senior, and general software engineering roles. Ask your recruiter which rounds are in your loop and whether the coding round is frontend, algorithmic, or both.
Treat these as practice prompts, not a guaranteed question bank. They are useful because they cover recurring Databricks-style patterns: async UI, system design depth, data structures, graph traversal, and data-platform products.
| Question | Round / role signal | What to practice |
|---|---|---|
| Build or design an autocomplete widget that fetches suggestions, debounces input, handles slow requests, recovers from errors, and prevents older responses from overwriting newer results. | Frontend phone screen | Request IDs, AbortController, cache, retries, loading/error states, API shape |
| Implement typeahead logic in CoderPad from a starter state object and input handler. Add caching, cache expiry, retry behavior, and race-condition handling across success, loading, and error states. | Senior full-stack / frontend systems | Business logic first, race handling, cache semantics, retry limits |
| Design a shared playlist where multiple users can add, remove, and reorder items at the same time. | Frontend systems | Collaboration model, WebSocket events, conflict handling, optimistic updates |
| Explain JavaScript closures, then render a nested comment list with CSS and vanilla JavaScript using an iterative approach. | Frontend coding | Closures, iterative tree traversal, DOM rendering, CSS structure |
| Build a dashboard view that reads live API data and explain the component model, data refresh strategy, routing, event handling, and HTTP API choices. | Pair programming / full-stack | API-backed dashboards, polling/SSE/WebSocket, state model, route boundaries |
| Solve a grid path-counting problem and compare a brute-force search with the optimized approach. | Problem solving | Backtracking, visited-state management, complexity analysis |
| Design an ad-click aggregation system with ingestion, aggregation windows, indexing, storage choice, scale, fault tolerance, and monitoring. | System design | Event ingestion, aggregation windows, storage, monitoring |
| Implement a configurable TicTacToe class for an MxN board with move handling, turn state, board updates, and win detection. | Coding | OOP state design, row/column counters, extensibility |
| Convert a route-planning problem into a graph problem, find a valid path, then extend the solution to account for different travel costs. | Algorithm | BFS, weighted search, path-cost tracking |
| Design an AutoML-style platform that accepts training requests, schedules jobs, stores experiments, tracks model versions, and isolates users. | System design | Job orchestration, model metadata, tenant isolation, resource control |
| Build a custom set that supports add, remove, contains, and iteration where an iterator sees a snapshot while the live set can still change. | L4 phone screen | Iterator snapshots, mutation semantics, Set/linked-list choices |
| Given a city grid with blocked cells and several transportation modes, choose the fastest route from source to destination and use cost as the tie-breaker. | Technical phone screen | BFS per mode, tie-breaking, grid traversal |
Implement an in-memory key-value map with put, get, and rolling five-minute call-rate metrics for reads and writes. | Machine coding | Sliding windows, timestamp buckets, concurrency discussion |
| Implement firewall-style allow/deny rules for individual IP addresses and CIDR ranges. | L5 technical phone screen | IP parsing, CIDR masks, rule precedence |
| Randomly connect several already-connected graphs into one graph so each possible ordering is equally likely. | Technical phone screen | Graph representation, random permutations, correctness of probabilities |
| Prepare for new-grad style loops that combine architecture discussion, DSA rounds, and behavioral interviews. | New grad SWE | DSA, system design communication, behavioral project stories |
| Prepare for senior data-platform rounds that can move from frontend/product discussion into distributed logs, analytics pipelines, and Spark-adjacent systems. | Senior SWE / data systems team | Data-platform system design, distributed systems, project depth |
The strongest frontend pattern is autocomplete/typeahead. It matches Databricks' official Front-End Code and Front-End Systems expectations: fetch remote data, manage async state, design client-server behavior, and implement business logic in CoderPad.
Start with the behavior before code:
For a CoderPad business-logic version, a small state machine is often clearer than a large component:
const cache = new Map();let activeRequestId = 0;let debounceTimer = null;const state = {query: '',status: 'idle', // idle | loading | success | empty | errorresults: [],error: null,};function setState(nextState) {Object.assign(state, nextState);}function isFreshCacheEntry(entry, now = Date.now()) {return entry != null && entry.expiresAt > now;}function handleInputChange(query) {setState({ query, error: null });clearTimeout(debounceTimer);if (query.trim() === '') {setState({ status: 'idle', results: [] });return;}debounceTimer = setTimeout(() => {fetchSuggestions(query);}, 250);}async function fetchSuggestions(query) {const cached = cache.get(query);if (isFreshCacheEntry(cached)) {setState({status: cached.results.length === 0 ? 'empty' : 'success',results: cached.results,});return;}const requestId = ++activeRequestId;setState({ status: 'loading' });try {const results = await fetchResults(query);if (requestId !== activeRequestId) {return;}cache.set(query, {results,expiresAt: Date.now() + 60_000,});setState({status: results.length === 0 ? 'empty' : 'success',results,});} catch (error) {if (requestId === activeRequestId) {setState({ status: 'error', error });}}}
Name the race condition explicitly. If the user types d, then da, then dat, the d request can finish last and overwrite newer results unless the app ignores stale responses or aborts old requests.
Good follow-up answers:
AbortController when the request layer supports it; still keep a request ID check because not every data source supports cancellation.Practice the implementation with Users Database, then practice the architecture with Autocomplete.
Use two tracks: frontend coding and general coding.
For frontend coding, practice:
For JavaScript and machine coding, practice:
For each coding problem, explain:
This is especially important for Databricks because many prompts start simple and then deepen through follow-ups. A working baseline is not enough if the next requirement forces a rewrite.
Databricks' official frontend systems description is unusually specific: client-server interfaces, API design, state management, data synchronization, and hands-on coding. That means a good answer should move between architecture and implementation.
Practice these Databricks-shaped designs:
| Design prompt | What to cover |
|---|---|
| Autocomplete across notebooks, tables, dashboards, and models | Query normalization, ranking, permissions, caching, cancellation, keyboard behavior, no-result states |
| Collaborative notebook editor | Cell model, output streaming, presence, conflicts, undo/redo, permissions, revision history |
| SQL editor result pane | Query lifecycle, cancellation, result limits, streaming/partial results, table virtualization, chart handoff |
| AI/BI dashboard | Tile lifecycle, cross-filtering, browser cache, parameterized queries, first paint, cache hit rate, concurrency |
| Workflow DAG UI | Graph layout, viewport virtualization, polling vs push, run history, status transitions, error recovery |
| Genie-style natural-language analytics | Prompt context, generated SQL review, result rendering, feedback loop, permission boundaries |
Use Databricks docs to make the answer concrete:
In a frontend system design round, spend less time drawing cloud boxes and more time on the browser contract:
Use the Front End System Design Playbook to structure the answer, then adapt the system to a data-product UI instead of a social feed or ecommerce page.
Databricks' interview prep page says behavioral interviews ask about real examples from past experience, problem solving, decision-making, learning, collaboration, and handling challenges. Prepare for project deep dives, design choices, collaboration, impact, conflict, and motivation for Databricks.
Prepare stories for:
For each story, write down:
If you have worked on editors, dashboards, data grids, query tools, charts, workflow builders, AI assistants, or internal platforms, use those examples first. They map cleanly to Databricks product work.
This plan is ordered by payoff, not by calendar week.
Before the interview, you should be able to:
Databricks frontend preparation should feel like practicing for a data product team: browser fundamentals, async state, data rendering, system design, and project judgment all matter. If you can build the typeahead cleanly, explain stale-response handling, design a large-result dashboard, and still solve graph-style coding prompts, you are covering the highest-value prep areas.

Netflix React interview questions are usually less about memorizing framework trivia and more about building practical UI, explaining state and data flow, handling performance constraints, and showing sound product judgment. Expect the exact loop to vary by team, but prepare for React, JavaScript, browser fundamentals, frontend system design, and culture/project discussion.
For deeper company-specific prep, use the Netflix Front End Interview Guide alongside this article.
Use each question as a working session: solve the baseline prompt, then explain what would change for larger data, weaker devices, unreliable APIs, accessibility requirements, and product experimentation.
Netflix frontend work spans streaming UI, discovery rows, playback controls, studio tooling, data dashboards, ads, games, experimentation, and internal workflows. The interview is not only checking whether you know React; it is also testing whether you can build a usable interface under constraints and explain the decisions behind it.
| Area | What to practice | What a complete answer shows |
|---|---|---|
| React implementation | Tables, lists, forms, carousels, charts, search, dashboards | You can ship a working baseline, keep state simple, and extend the component without rewriting it. |
| Data handling | Fetching, grouping, filtering, derived data, retries, stale responses | You understand API-backed UI and avoid state that drifts from the source of truth. |
| Rendering performance | Memoization, virtualization, throttling, debouncing, image loading | You measure before optimizing and know which bottleneck each technique addresses. |
| Browser fundamentals | Event loop, DOM APIs, storage, layout, accessibility, security | You can reason beyond React abstractions when the browser behavior matters. |
| System design | Playback, discovery, search, dashboards, recommendations | You can move from user flow to API contracts, cache behavior, metrics, and rollout. |
| Culture/project discussion | Feedback, disagreement, ownership, judgment, ambiguity | You can explain the decision-making behind your work, not just the final result. |
A table with 20 rows is simple. A table with expandable JSON, async filters, keyboard navigation, partial failures, and slow rows gives a better signal of how you build.
Use these as practice prompts, not a guaranteed question bank. For each one, timebox a working baseline first, then talk through tradeoffs, edge cases, accessibility, performance, and testing.
[2, 4, 5, 2, 3, 4], produce a frequency map and render it as a histogramUse this sequence to turn each prompt into a serious interview drill:
Aim for working code first, then explain data growth, network failure, changing requirements, accessibility, and tests.
Start with a simple data model:
id for stable row identityconfig or metadata object for expandable JSONKeep the first version simple. Fetch data, render rows, and show loading, error, and empty states. Use semantic table markup if the data is truly tabular. Keep row expansion keyed by stable IDs, not row index, because sorting and filtering can reorder the rows.
Then talk through follow-ups:
Set of expanded row IDs. Do not copy the full row data into expansion state.aria-expanded, and keyboard-reachable actions.Name these choices while coding. For example: "I am storing expanded row IDs instead of expanded row objects so sorting, filtering, and refetching do not corrupt expansion state."
Practice this with Data Table, then add your own expandable JSON follow-up after the base solution works.
The histogram-style prompt checks whether you can move from raw data to a useful UI. It also reveals whether you can write JavaScript cleanly under time pressure.
Start with the transformation:
function countByValue(values) {return values.reduce((counts, value) => {counts[value] = (counts[value] ?? 0) + 1;return counts;}, {});}
Then convert the object into sorted display data:
const bars = Object.entries(counts).map(([value, count]) => ({ value: Number(value), count })).sort((a, b) => a.value - b.value);
The habits matter more than the exact rendering code:
If the interviewer lets you use React, split the work into a data transform and a presentational chart component. If they ask for vanilla JavaScript, explain the data shape before writing DOM code.
React interviews still lean on JavaScript because many React bugs come from JavaScript, browser behavior, or the network.
Practice these questions:
this work in JavaScript, and how does Function.prototype.bind change it?bind polyfill. What edge cases matter?localStorage, sessionStorage, cookies, and in-memory cache?For practice, work through useThrottle, bind, and the React quiz questions. Tie each concept to a UI bug.
For closures, use a timer, event listener, or async request example. Show how a callback can read an older value and how to fix it with a functional state update, a ref, or a corrected dependency list. For prototypes, explain lookup and mutation without making it sound like a pattern you would reach for in modern React code. For the event loop, explain how promise callbacks and timers affect loading spinners, input handlers, and batched updates.
For storage, do not just compare lifetimes. Explain what belongs where:
localStorage for small, non-sensitive preferences.That difference is important in Netflix-style UI because the wrong state location can break profile switching, stale filters, analytics attribution, or experiment behavior.
Practice these prompts:
Before coding, say what you are optimizing for. For example: "I will keep selected IDs in state instead of copying whole item objects, because the source list can change after a refetch."
For broader practice, use the React coding interview questions and spend extra time on table, list, transfer, histogram, autocomplete, and carousel-style components.
A credible React answer has a few visible habits:
Avoid early abstraction. In a 45-minute interview, build one clear component, extract a helper when duplication appears, and explain where production code would separate concerns.
Before coding, decide where each state value belongs:
| State | Good default | Watch out for |
|---|---|---|
| Raw API data | Server/query state or a top-level component state | Copying rows into multiple local states. |
| Filter text | Local state, sometimes URL state | Applying filters directly inside event handlers and losing source data. |
| Selected rows | Set of stable IDs | Storing whole objects and breaking selection after refetch. |
| Expanded rows | Set of stable IDs | Using array indices as identity. |
| Sort | Local or URL state | Sorting raw data in place. |
| Loading/error | Data-fetching layer or component state | Hiding partial failures. |
State these choices during the interview; the interviewer cannot give credit for reasoning they never hear.
For Netflix-style UI, account for loading speed, input responsiveness, memory, and device constraints.
Practice these questions:
For system design, start from the user flow, then cover component boundaries, data contracts, cache behavior, loading states, failure modes, accessibility, metrics, and rollout.
Structure the answer like this:
Avoid treating "use memoization" as a complete answer. Memoization helps only when referential stability or expensive computation is the bottleneck. For image-heavy UI, network, decoding, layout stability, and focus behavior may matter more.
Cover these decisions:
Practice the base structure with Autocomplete, then adapt the answer to profiles, maturity restrictions, localization, personalization, and multiple device types.
Prepare stories where the technical decision and the human context are both clear.
Practice these questions:
Use the Behavioral Interview Playbook to keep each story concrete: context, constraint, decision, result, and what changed afterward.
"I built the dashboard and improved performance" is not enough. Interviewers need the decision trail.
For each project, prepare:
For a performance story, name the metric: interaction latency, JavaScript bundle size, image bytes, table render time, or error rate. Each points to a different bottleneck and fix.
For disagreement stories, explain what information each side had, how shared context was created, what decision was made, and how you supported it afterward.
Start by mapping your interview to the team. A Studio tooling role, TV UI role, ads role, and discovery role can all ask React questions, but the examples and tradeoffs will differ.
Use this preparation order:
Connect React and behavioral preparation: what you built, why it mattered, what constraints shaped it, and how you handled the product and team tradeoffs around it.
| Round type | How to prepare |
|---|---|
| Recruiter screen | Know why this role, why Netflix, what team domain interests you, and what culture points you can discuss honestly. |
| React coding | Practice one working component per session. Add a follow-up after the baseline works. Speak through state choices. |
| JavaScript/browser | Explain concepts through UI bugs: stale closures, event loop timing, storage misuse, DOM performance, XSS. |
| Frontend system design | Practice verbally: user flow, API shape, state model, cache, loading, failure, accessibility, metrics, rollout. |
| Hiring manager/project | Prepare two or three stories with decision, tradeoff, result, and lesson. |
If your interview is soon, prioritize prompts that transfer across teams:
bind, storage, XSS, and async request cancellation.After each coding drill, write a short self-review:
This is more useful than collecting hundreds of React trivia questions.
Yes. React can appear in frontend, UI engineer, data visualization, and full-stack loops. The questions are often practical: build a component, fetch data, manage state, explain hooks, improve rendering, or discuss product constraints.
Some loops include algorithms, but frontend candidates should not prepare only with LeetCode. Practice JavaScript, React components, browser behavior, async UI, performance, and frontend system design.
Hooks, state ownership, async data fetching, memoization, derived state, context tradeoffs, error boundaries, list rendering, accessibility, and performance measurement.
Yes. Read it before the recruiter or hiring-manager conversation, then prepare specific stories about feedback, disagreement, judgment, autonomy, and ownership. Generic culture answers are easy to identify.

Frontend LLD questions are machine coding interview questions where you design and build a small UI feature from scratch. In frontend interviews, "LLD" usually means proving that you can break a component into requirements, state, interactions, edge cases, and readable code before the timer runs out.
This guide covers five practical frontend LLD problems:
Each one includes the requirement, a two-minute planning outline, a React solution, and the mistakes interviewers notice quickly.
Use this article as a practice guide, then solve more user interface coding interview questions on GreatFrontEnd in a real coding environment.
LLD stands for low-level design. In backend interviews, it often means designing classes, APIs, relationships, and object behavior. In frontend interviews, the same term is usually applied to UI implementation.
For a frontend developer, frontend LLD usually tests whether you can:
That is why frontend LLD questions overlap heavily with React machine coding round questions and solutions. The interviewer is not only checking whether the component works. They are checking whether the implementation has a design.
If you are preparing for LLD for frontend developer roles, treat each prompt as both a design problem and a coding problem. The same prompts often appear under names like frontend machine coding round questions in React, React live coding interview questions, or React UI coding questions.
Before writing React code, spend two minutes turning the prompt into a plan.
Say what you are building in one sentence.
For example: "I will build an autocomplete input that fetches suggestions after the user types, shows loading and empty states, and lets the user select a suggestion."
This catches misunderstandings early.
Most frontend machine coding round questions fail in state design. List the important states before coding:
Avoid storing the same idea twice. If visibleItems can be derived from items and filter, derive it.
Keep it practical:
AutocompleteSearchInputSuggestionsListSuggestionItem
You do not need a production-grade architecture. You need boundaries that make the code easier to review.
Do not start with polish. Start with the smallest demo that proves the requirement:
This rhythm is what separates strong React live coding interview questions from half-finished code.
Build a list that loads the next page of items when the user scrolls near the bottom. Show loading, error, and "no more results" states.
This is a common frontend LLD problem because it tests async state, browser APIs, cleanup, duplicate request prevention, and edge cases around slow responses.
items, page, status, and hasMore in state.page changes.IntersectionObserver on a sentinel element at the bottom of the list.hasMore becomes false.import { useEffect, useRef, useState } from 'react';export default function InfiniteScrollList({ fetchPage }) {const [items, setItems] = useState([]);const [page, setPage] = useState(1);const [status, setStatus] = useState('idle'); // idle | loading | success | errorconst [hasMore, setHasMore] = useState(true);const sentinelRef = useRef(null);useEffect(() => {let cancelled = false;async function loadPage() {setStatus('loading');try {const result = await fetchPage(page);if (cancelled) {return;}setItems((currentItems) => [...currentItems, ...result.items]);setHasMore(result.hasMore);setStatus('success');} catch {if (!cancelled) {setStatus('error');}}}loadPage();return () => {cancelled = true;};}, [fetchPage, page]);useEffect(() => {const sentinel = sentinelRef.current;if (sentinel == null || status !== 'success' || !hasMore) {return;}const observer = new IntersectionObserver(([entry]) => {if (entry.isIntersecting) {// Stop observing until the next page finishes loading.observer.unobserve(sentinel);setPage((currentPage) => currentPage + 1);}},// Start loading before the user reaches the absolute bottom.{ rootMargin: '200px' },);observer.observe(sentinel);return () => {observer.disconnect();};}, [hasMore, status]);return (<section><ul>{items.map((item) => (<li key={item.id}>{item.title}</li>))}</ul>{status === 'loading' && <p>Loading...</p>}{status === 'error' && <p>Unable to load more items.</p>}{status === 'success' && items.length === 0 && <p>No results found.</p>}{items.length > 0 && !hasMore && <p>No more results.</p>}<div ref={sentinelRef} aria-hidden="true" /></section>);}
IntersectionObserver.items value instead of a functional state update.In a real interview, call out pagination details explicitly: "I am assuming the API returns { items, hasMore }. If it returns total count or next cursor instead, I will adapt the state model."
Build a star rating component that allows users to select a rating from one to five. It should show hover preview, selected value, and support a controlled value prop.
Practice this problem directly on GreatFrontEnd: Star Rating in React.
max, value, and onChange.import { useState } from 'react';export default function StarRating({ max = 5, value, onChange }) {const [internalValue, setInternalValue] = useState(0);const [hoveredValue, setHoveredValue] = useState(0);const selectedValue = value ?? internalValue;const displayValue = hoveredValue || selectedValue;function selectRating(nextValue) {if (value == null) {setInternalValue(nextValue);}onChange?.(nextValue);}return (<fieldset><legend>Rating</legend><divonMouseLeave={() => {setHoveredValue(0);}}>{Array.from({ length: max }, (_, index) => {const rating = index + 1;const isFilled = rating <= displayValue;return (<buttonaria-label={`${rating} star${rating === 1 ? '' : 's'}`}aria-pressed={rating === selectedValue}key={rating}onClick={() => {selectRating(rating);}}onMouseEnter={() => {setHoveredValue(rating);}}type="button">{isFilled ? '★' : '☆'}</button>);})}</div></fieldset>);}
value prop is provided.type="button", which can accidentally submit a parent form.A strong follow-up is half-star ratings. The design change is clear: replace each full-star button with either two hit areas or pointer-position logic, then store values in 0.5 increments.
Build an autocomplete search input that fetches suggestions as the user types. It should debounce requests, cancel stale requests, show loading and empty states, and allow keyboard selection.
Autocomplete is one of the best frontend LLD questions because it touches forms, async behavior, race conditions, keyboard interactions, positioning, and accessibility. For a deeper architecture discussion, read GreatFrontEnd's Autocomplete front end system design question.
query, suggestions, status, and activeIndex in state.AbortController so older requests cannot overwrite newer results.import { useEffect, useState } from 'react';export default function Autocomplete({ search }) {const [query, setQuery] = useState('');const [suggestions, setSuggestions] = useState([]);const [status, setStatus] = useState('idle'); // idle | loading | success | errorconst [activeIndex, setActiveIndex] = useState(-1);useEffect(() => {const trimmedQuery = query.trim();if (trimmedQuery.length < 2) {setSuggestions([]);setStatus('idle');setActiveIndex(-1);return;}// AbortController lets us cancel this request if the user types a newer query.const controller = new AbortController();// Debounce the request so every keystroke does not call the API.const timeoutId = window.setTimeout(async () => {setStatus('loading');try {const results = await search(trimmedQuery, {signal: controller.signal,});setSuggestions(results);setStatus('success');setActiveIndex(results.length > 0 ? 0 : -1);} catch (error) {if (error?.name !== 'AbortError') {setStatus('error');}}}, 250);return () => {// Cancel both the scheduled search and any in-flight request for the old query.window.clearTimeout(timeoutId);controller.abort();};}, [query, search]);function selectSuggestion(suggestion) {setQuery(suggestion.label);setSuggestions([]);setStatus('idle');setActiveIndex(-1);}function handleKeyDown(event) {if (suggestions.length === 0) {return;}if (event.key === 'ArrowDown') {event.preventDefault();setActiveIndex((currentIndex) =>Math.min(currentIndex + 1, suggestions.length - 1),);}if (event.key === 'ArrowUp') {event.preventDefault();setActiveIndex((currentIndex) => Math.max(currentIndex - 1, 0));}if (event.key === 'Enter' && activeIndex >= 0) {event.preventDefault();selectSuggestion(suggestions[activeIndex]);}if (event.key === 'Escape') {setSuggestions([]);setActiveIndex(-1);}}return (<div><label htmlFor="search">Search</label><inputaria-activedescendant={activeIndex >= 0? `search-suggestion-${suggestions[activeIndex].id}`: undefined}aria-autocomplete="list"aria-controls="search-suggestions"aria-expanded={suggestions.length > 0}autoComplete="off"id="search"onChange={(event) => {setQuery(event.target.value);}}onKeyDown={handleKeyDown}role="combobox"value={query}/>{status === 'loading' && <p>Loading suggestions...</p>}{status === 'error' && <p>Unable to load suggestions.</p>}{status === 'success' && suggestions.length === 0 && (<p>No suggestions found.</p>)}{suggestions.length > 0 && (<ul id="search-suggestions" role="listbox">{suggestions.map((suggestion, index) => (<liaria-selected={index === activeIndex}id={`search-suggestion-${suggestion.id}`}key={suggestion.id}onMouseDown={(event) => {// Keep focus on the input while selecting with the mouse.event.preventDefault();selectSuggestion(suggestion);}}role="option">{suggestion.label}</li>))}</ul>)}</div>);}
onMouseDown avoids that common issue.If the interviewer asks for production-level accessibility, discuss the full combobox pattern and keyboard expectations. In a timed React live coding interview, a clear partial implementation plus the right explanation is usually better than a broken full implementation.
Build a list where users can reorder items by dragging one item and dropping it before another item.
This is a useful LLD problem because it tests list state, stable keys, event handling, and how well you can avoid overcomplicating the first version.
import { useState } from 'react';const initialItems = [{ id: 'todo', label: 'Todo' },{ id: 'doing', label: 'Doing' },{ id: 'review', label: 'Review' },{ id: 'done', label: 'Done' },];export default function DragAndDropList() {const [items, setItems] = useState(initialItems);const [draggedId, setDraggedId] = useState(null);function moveItemBefore(targetId) {if (draggedId == null || draggedId === targetId) {return;}setItems((currentItems) => {const draggedItem = currentItems.find((item) => item.id === draggedId);if (draggedItem == null) {return currentItems;}const remainingItems = currentItems.filter((item) => item.id !== draggedId,);// Find the target after removing the dragged item so the insertion index is correct.const targetIndex = remainingItems.findIndex((item) => item.id === targetId,);if (targetIndex === -1) {return currentItems;}return [...remainingItems.slice(0, targetIndex),draggedItem,...remainingItems.slice(targetIndex),];});}return (<ul>{items.map((item) => (<lidraggablekey={item.id}onDragEnd={() => {setDraggedId(null);}}onDragOver={(event) => {event.preventDefault();}}onDragStart={() => {setDraggedId(item.id);}}onDrop={() => {moveItemBefore(item.id);}}>{item.label}</li>))}</ul>);}
items array with splice instead of returning a new array.If the prompt expects a polished implementation, add a drop zone after the final item so the user can move an item to the end. If the prompt expects mobile support, explain that you would likely use pointer events or a well-tested drag-and-drop library in production.
For related practice, solve Transfer List in React, which tests similar item movement and state updates.
Build a toast notification system that can show multiple messages, auto-dismiss each toast after a delay, and allow manual dismissal.
This frontend LLD question tests queues, timers, cleanup, rendering a stack, and accessibility for status updates.
showToast function.setTimeout.import { useCallback, useEffect, useRef, useState } from 'react';export default function ToastDemo() {const [toasts, setToasts] = useState([]);const nextIdRef = useRef(1);// Keep timer IDs outside render state so they can be cleared reliably.const timersRef = useRef(new Map());const dismissToast = useCallback((id) => {const timerId = timersRef.current.get(id);if (timerId != null) {window.clearTimeout(timerId);timersRef.current.delete(id);}setToasts((currentToasts) =>currentToasts.filter((toast) => toast.id !== id),);}, []);const showToast = useCallback((message, variant = 'info') => {const id = nextIdRef.current;nextIdRef.current += 1;setToasts((currentToasts) => [...currentToasts,{ id, message, variant },]);const timerId = window.setTimeout(() => {dismissToast(id);}, 4000);timersRef.current.set(id, timerId);},[dismissToast],);useEffect(() => {return () => {timersRef.current.forEach((timerId) => {window.clearTimeout(timerId);});timersRef.current.clear();};}, []);return (<section><buttononClick={() => {showToast('Profile saved', 'success');}}type="button">Show toast</button><div aria-live="polite" aria-relevant="additions" role="status">{toasts.map((toast) => (<div data-variant={toast.variant} key={toast.id}><span>{toast.message}</span><buttonaria-label="Dismiss notification"onClick={() => {dismissToast(toast.id);}}type="button">×</button></div>))}</div></section>);}
isToastVisible, which cannot represent multiple toasts.For a stronger answer, mention how you would expose this through context in a real app:
ToastProvideruseToast()showToast()dismissToast()ToastViewport
That shows you understand the difference between an interview implementation and a reusable application service.
When practicing react machine coding round questions and solutions, do not only ask "does it work?" Ask whether the solution will survive follow-up questions.
| Component | First follow-up | What it tests |
|---|---|---|
| Infinite scroll | Add retry and cursor pagination | Async state and API assumptions |
| Star rating | Support half-star ratings | Component API and event handling |
| Autocomplete search | Add caching and stale response handling | Async correctness and performance |
| Drag-and-drop list | Move items across two lists | Data modeling and immutable updates |
| Toast notification | Add toast placement and max queue size | State queues and reusable APIs |
Good frontend LLD preparation means practicing the base problem and then asking: "What would break if the interviewer adds one more requirement?"
If you have one week before a frontend LLD or React machine coding round, use this sequence:
Day 1: Basic state and events Build counter, accordion, tabs, todo list, and star rating.
Day 2: Lists and derived state Build transfer list, selectable cells, data table, and drag-and-drop reorder.
Day 3: Async UI Build autocomplete, job board, infinite scroll, and a search results page.
Day 4: Timers and queues Build progress bars, stopwatch, traffic light, and toast notifications.
Day 5: Accessibility pass Revisit tabs, accordion, modal dialog, autocomplete, and star rating.
Day 6: Timed mocks Pick two problems and solve each in 45 to 60 minutes.
Day 7: Review and redo Redo the weakest problem without looking at your previous code.
GreatFrontEnd has many of these as browser-based practice questions. Start with React coding interview questions, then add the broader UI coding question set.
In frontend LLD interviews, the strongest candidates make their thinking easy to follow. They do not simply type React code quickly.
Interviewers usually look for:
The best habit is simple: say the design before you code it. A practical sentence like "I will keep hover preview separate from committed rating because they represent different states" gives the interviewer confidence that your code is intentional.
Frontend LLD questions are not a different category from React machine coding questions. They are the design layer inside the coding round.
If you can clarify requirements, model state, build the main interaction, handle edge cases, and explain trade-offs while coding, you are preparing for the round that many frontend interviews now use to separate React familiarity from real UI engineering skill.

This guide is a practical set of TypeScript interview questions for senior frontend developers. In 2026, senior TypeScript interviews are less about defining Partial<T> and more about using the type system to model product states, prevent invalid component APIs, and make refactors safer.
If you are preparing for TypeScript interview questions for experienced roles, focus on code problems. Interviewers want to see how you design constraints, how you narrow unsafe data, and when you choose a simple type over a clever one.
If you want more hands-on practice after this guide, use GreatFrontEnd's TypeScript interview questions.
At junior and mid-level, TypeScript questions often check syntax: interface vs type, unknown vs any, optional properties, or basic generics.
At senior and staff level, the prompt usually sounds more like production code:
That is the pattern behind the TypeScript coding interview questions below.
How it appears in an interview: "Our dashboard uses isLoading, error, and data, but invalid states keep slipping through. Refactor the type."
type RemoteData<T> =| { status: 'idle' }| { status: 'loading' }| { status: 'success'; data: T }| { status: 'error'; error: Error };function assertNever(value: never): never {throw new Error(`Unhandled state: ${JSON.stringify(value)}`);}function renderUsers(state: RemoteData<Array<{ id: string; name: string }>>) {switch (state.status) {case 'idle':return 'Choose a team';case 'loading':return 'Loading users';case 'success':return state.data.map((user) => user.name).join(', ');case 'error':return state.error.message;default:return assertNever(state);}}
What interviewers look for: You should remove impossible states instead of documenting them. success must always have data; error must always have error; loading should not accidentally carry stale data unless that is an explicit product decision.
The senior signal is exhaustiveness. If a future engineer adds { status: 'refreshing' }, the assertNever line makes incomplete rendering logic fail at compile time.
pick helper without losing key safetyHow it appears in an interview: "Implement pick(obj, keys) so keys must exist on the object and the return type only contains those keys."
function pick<T extends object, K extends keyof T>(obj: T,keys: readonly K[],): Pick<T, K> {const result = {} as Pick<T, K>;for (const key of keys) {result[key] = obj[key];}return result;}const user = {id: 'u_1',name: 'Ada',role: 'admin',active: true,};const summary = pick(user, ['id', 'name'] as const);// summary is { id: string; name: string }
What interviewers look for: This tests generic constraints and keyof. A weaker answer uses string[] for keys and returns Partial<T>, which loses the reason TypeScript is useful here. A strong answer preserves the exact key union.
The follow-up is usually about mutation. The cast inside the function is acceptable because JavaScript object construction is dynamic, but the public API remains precise. Senior candidates can explain that boundary instead of pretending no assertion is ever allowed.
How it appears in an interview: "We need an endpoint that updates a user profile. It should allow name, email, and timezone, but never id, createdAt, or role."
type User = {id: string;name: string;email: string;timezone: string;role: 'member' | 'admin';createdAt: string;};type EditableUserFields = Pick<User, 'name' | 'email' | 'timezone'>;type UpdateUserPayload = Partial<EditableUserFields>;async function updateUser(id: User['id'], payload: UpdateUserPayload) {return fetch(`/api/users/${id}`, {method: 'PATCH',body: JSON.stringify(payload),});}updateUser('u_1', { timezone: 'Asia/Kolkata' });
What interviewers look for: Utility types should express intent. Partial<User> is too broad because it allows protected fields. Pick plus Partial says, "Only these fields are editable, and each is optional in a patch."
This is one of the most common TypeScript coding questions because it mirrors real frontend work: form models, DTOs, optimistic updates, and API client boundaries.
infer to unwrap async resultsHow it appears in an interview: "Given a service function, derive the resolved response type without copying it manually."
async function getCurrentUser() {return {id: 'u_1',name: 'Grace',permissions: ['billing:read', 'team:write'] as const,};}type AsyncReturn<T> = T extends (...args: infer _Args) => Promise<infer R>? R: never;type CurrentUser = AsyncReturn<typeof getCurrentUser>;function canEditTeam(user: CurrentUser) {return user.permissions.includes('team:write');}
What interviewers look for: This tests whether you understand conditional types as relationships between inputs and outputs. infer R captures the resolved value from a promise-returning function.
A practical follow-up: TypeScript already has ReturnType<T> and Awaited<T>, so this can also be written as:
type CurrentUser = Awaited<ReturnType<typeof getCurrentUser>>;
The senior answer names the built-in utility and explains when a custom helper is still useful.
How it appears in an interview: "Create a typed event map for a settings object. Each key should produce an on<Key>Changed handler."
type ChangeHandlers<T extends object> = {[K in keyof T as `on${Capitalize<string & K>}Changed`]: (nextValue: T[K],) => void;};type Settings = {theme: 'light' | 'dark';pageSize: 25 | 50 | 100;showArchived: boolean;};type SettingsHandlers = ChangeHandlers<Settings>;const handlers: SettingsHandlers = {onThemeChanged: (theme) => console.log(theme),onPageSizeChanged: (pageSize) => console.log(pageSize),onShowArchivedChanged: (showArchived) => console.log(showArchived),};
What interviewers look for: This combines mapped types, key remapping, template literal types, and indexed access types. It is a strong senior prompt because the runtime idea is simple, but the type-level transformation requires precision.
The judgment part matters too. This pattern is useful for design-system APIs, event maps, analytics names, and generated clients. It is probably overkill for one local component.
How it appears in React TypeScript interview questions: "Create a button that can behave like a link or a real button, but never both."
type BaseProps = {children: React.ReactNode;variant?: 'primary' | 'secondary';};type LinkButtonProps = BaseProps & {href: string;onClick?: never;};type ActionButtonProps = BaseProps & {href?: never;onClick: () => void;};type ButtonProps = LinkButtonProps | ActionButtonProps;function Button(props: ButtonProps) {if (props.href !== undefined) {return <a href={props.href}>{props.children}</a>;}return <button onClick={props.onClick}>{props.children}</button>;}
What interviewers look for: Prop types can define product constraints instead of merely documenting them. never prevents callers from passing both href and onClick, and the href check narrows the union inside the component.
This is a better answer than a single prop bag with href?: string and onClick?: () => void, because the weak version makes every invalid combination somebody else's runtime problem.
How it appears in an interview: "We have variants in a design system. Keep the object literal narrow, but verify that every variant exists."
type ButtonVariant = 'primary' | 'secondary' | 'danger';const buttonClasses = {primary: 'bg-blue-600 text-white',secondary: 'bg-slate-100 text-slate-900',danger: 'bg-red-600 text-white',} satisfies Record<ButtonVariant, string>;function getButtonClass(variant: ButtonVariant) {return buttonClasses[variant];}
What interviewers look for: This problem checks whether you know the difference between annotation and validation. satisfies verifies the object conforms to Record<ButtonVariant, string> while preserving useful inference from the original object.
In a senior interview, expect a follow-up: "What happens when someone adds ghost to ButtonVariant?" The object must now include ghost, so the compiler catches the incomplete design-system map.
unknown is better than anyHow it appears in an interview: "We parse JSON from local storage. Type it safely."
function parseJson(value: string): unknown {return JSON.parse(value);}type Preferences = {theme: 'light' | 'dark';};function isPreferences(value: unknown): value is Preferences {return (typeof value === 'object' &&value !== null &&'theme' in value &&(value.theme === 'light' || value.theme === 'dark'));}const parsed = parseJson(localStorage.getItem('preferences') ?? '{}');if (isPreferences(parsed)) {parsed.theme;}
What interviewers look for: any says "trust me" and disables checking. unknown says "prove it first." Senior TypeScript work often happens at boundaries: network responses, storage, third-party scripts, feature flags, analytics payloads, and CMS content.
The strong answer pairs unknown with a narrowing function or schema validator. TypeScript cannot make untrusted runtime data safe by itself.
How it appears in an interview: "Our app has several status constants. Should we use an enum, a union type, or an as const object?"
const ORDER_STATUS = {Draft: 'draft',Paid: 'paid',Shipped: 'shipped',Cancelled: 'cancelled',} as const;type OrderStatus = (typeof ORDER_STATUS)[keyof typeof ORDER_STATUS];function getStatusLabel(status: OrderStatus) {switch (status) {case ORDER_STATUS.Draft:return 'Draft';case ORDER_STATUS.Paid:return 'Paid';case ORDER_STATUS.Shipped:return 'Shipped';case ORDER_STATUS.Cancelled:return 'Cancelled';}}
What interviewers look for: In frontend code, string literal unions and as const objects often fit better than regular enums because they keep API values as plain strings and compose cleanly with other type utilities.
A senior answer should not turn this into a rule. Enums can still be useful in shared TypeScript codebases, but for UI state, analytics event names, API statuses, and component variants, literal unions are usually easier to compose with mapped types, discriminated unions, and template literal types.
Use this checklist for TypeScript interview questions for 5 years experience and above:
keyof, indexed access types, and constrained type parameters.Partial, Required, Pick, Omit, Record, ReturnType, Parameters, and Awaited.infer, even if you do not write them every day.unknown at unsafe boundaries and narrow before use.as const and literal unions are cleaner than runtime enums.The best senior TypeScript answers are practical. They prevent invalid states, preserve inference, and make the next refactor less risky.
When practicing TypeScript coding questions, do not memorize every utility type in isolation. Start with a real constraint: which states are impossible, which keys are allowed, which component props conflict, which runtime values are untrusted. Then use TypeScript to encode that constraint clearly.
For more practice, head to GreatFrontEnd's TypeScript interview questions and work through problems with the same mindset: code first, types as guardrails, and explanations that connect back to production frontend work.

No. Frontend development is not dying in 2026. Simple UI assembly is getting cheaper. The harder parts remain: browser behavior, accessibility, state, performance, and product trade-offs.
That distinction matters. Most "will AI replace frontend developers" arguments confuse two different jobs:
AI can generate React components, Tailwind layouts, landing page sections, form markup, and first-pass prototypes. That helps. It also solves the easiest part of many frontend tasks.
The harder part is still engineering: clarifying requirements, designing component boundaries, reasoning about state, debugging CSS, handling edge cases, reviewing generated code, and shipping interfaces that hold up outside a demo.
The better question is: which version of frontend development is dying?
The version that is most exposed looks like this:
That work is easier to automate because the requirements are narrow and the review is mostly visual. If the screen looks close enough, the task feels done.
Frontend is an attractive target for AI. There is a huge amount of HTML, CSS, JavaScript, React, and Tailwind code online. Many UI patterns are well documented. A lot of frontend work also sits close to the edge of the system, so teams are more comfortable generating a first pass there than in payments, infrastructure, or security-critical paths.
But not all frontend work has the same risk. A static marketing page, an admin CRUD screen, and a support dashboard are different from browser-native products like Figma, Linear, Google Docs, Spotify, or a complex AI workspace. The first group is often a thin layer over data. The second group has deep client-side state, real-time collaboration, offline behavior, streaming updates, performance constraints, and many interaction edge cases.
The harder work looks different:
That second group still needs frontend engineers. It may need fewer people typing boilerplate, but it needs people who can own the outcome.
There is no single clean metric called "frontend developer demand." Job titles vary by company, country, seniority, and whether the role is called frontend, full stack, web developer, UI engineer, product engineer, or software engineer.
Still, the available data does not support the claim that frontend development is disappearing.
| Signal | What it says | How to read it |
|---|---|---|
| BLS web developers and digital designers | Overall employment is projected to grow 7% from 2024 to 2034, with about 14,500 openings per year. | This is a US source, but it is a useful labor-market signal for web and interface work. |
| BLS software developers, QA analysts, and testers | Employment is projected to grow 15% from 2024 to 2034, with about 129,200 openings per year. | Frontend sits inside broader software work, and software demand is not collapsing. |
| World Economic Forum Future of Jobs 2025 | Software and applications developers are listed among the fastest-growing roles by 2030. | Employers expect technology roles to keep growing even as AI changes the work. |
| LinkedIn U.S. Software Engineer Talent Landscape 2026 | SWE hiring momentum has slowed, entry pathways are tightening, and AI-adjacent roles are growing. | The market is not dead, but juniors and narrow specialists face a harder bar. |
| Indeed Global Labor Market and Workforce Trends 2026 | US tech job postings moved from boom to bust, and a larger share of tech postings now ask for at least five years of experience. | Current hiring data supports the experience-bar argument better than broad replacement claims. |
| Stack Overflow Developer Survey 2025 | 84% of respondents use or plan to use AI tools, but more developers distrust AI accuracy than trust it. | AI is now part of development, but human verification remains central. |
| DORA State of AI-assisted Software Development 2025 | AI works as an amplifier of an organization's existing engineering strengths and weaknesses. | AI helps teams with good systems, but it does not remove the need for review, testing, and delivery discipline. |
| GitHub Octoverse 2025 | TypeScript became GitHub's most used language by contributor count in August 2025; JavaScript and TypeScript remain the largest combined ecosystem. | The web stack is not fading. It is becoming more typed and production-oriented. |
| WebAIM Million 2026 | 95.9% of the top one million home pages had detected WCAG failures, with 56.1 errors per page on average. | The web still has a massive quality gap, especially around accessibility. |
Taken together, the data does not show frontend disappearing. It shows a tighter market with higher expectations. AI is now part of development, entry-level pathways are harder, and teams still need people who can review, test, and improve the code before users touch it.
Frontend has been declared dead many times.
WYSIWYG editors like Dreamweaver promised that visual editing would remove the need to write HTML. WordPress made publishing dramatically easier. Offshore outsourcing changed how companies staffed web projects. Bootstrap made decent-looking layouts available to everyone. Webflow and no-code tools let non-engineers create polished sites. Now AI can generate a full screen from a prompt.
Each wave removed repetitive work. None removed the need for people who understand how the web behaves.
What changed was the baseline. In the early web, knowing HTML and CSS was enough to be useful. Later, frontend developers needed responsive design, JavaScript, browser APIs, build tools, design systems, accessibility, performance, analytics, API integration, security awareness, and framework fluency.
AI is another abstraction wave. It removes some manual work. It also creates more code that someone has to review, integrate, test, and maintain.
AI will replace some frontend tasks. It will not replace every frontend developer.
These tasks are already easier to automate:
Use it. Just do not confuse a generated first pass with finished work.
Faster code generation does not remove the rest of the job. In production, the expensive part is often not typing the component. It is deciding what the component should do, how it should fail, whether the state model is correct, whether keyboard users can operate it, whether it performs under load, and whether the implementation will still make sense after three more requirements are added.
Stack Overflow's 2025 survey reflects that split. AI usage is widespread, but only a small fraction of developers highly trust AI output. Most serious teams still review generated code before shipping it.
AI-generated frontend code can be impressive in a screenshot and still fail in the browser.
A generated layout can look fine at 1440px with short English labels and then break with long content, browser zoom, a narrow container, a sticky header, a nested scroll area, or an unexpected image ratio.
The problem is that AI often predicts a plausible layout pattern without knowing the actual page, the container it will live inside, the device constraints, or the user's path through the interface. CSS generated by AI can look right in isolation and still be wrong inside the product.
The hard parts of CSS are constraint problems:
width, max-width, or min-width: 0?AI can suggest CSS. A frontend engineer has to know whether it is stable. If this is a weak spot, start with common CSS mistakes front end engineers make.
Accessibility is a clear example. The 2026 WebAIM Million report found detected WCAG failures on 95.9% of top home pages. It also found that pages using ARIA had significantly more detected errors on average than pages without ARIA.
That does not mean ARIA is bad. It means accessibility is easy to get wrong when people add attributes without understanding the interaction model.
A modal is not accessible because it has role="dialog". A combobox is not accessible because the markup contains aria-expanded. A menu is not accessible because the items look clickable.
You still need to test labels, focus order, keyboard behavior, escape behavior, screen reader names, error messages, contrast, reduced motion, and disabled states. Research on AI-assisted accessible coding has found similar issues: developers often fail to prompt for accessibility, skip manual validation steps, or cannot verify whether the generated UI is compliant.
AI can generate a form. It cannot reliably decide whether the form is too long, whether the error message is useful, whether the destructive action needs confirmation, whether a dropdown should be a combobox, or whether the user should see an empty state before a loading state.
Those choices are product judgment. They come from understanding users, constraints, and trade-offs.
Frontend bugs often live in transitions:
These bugs do not show up in a static screenshot. They show up when a user interacts with the UI in the wrong order, on a slow network, with real data.
The more product state a frontend owns, the more these combinations matter. Auth state, cached server data, optimistic updates, form drafts, route transitions, animations, feature flags, and WebSocket events can all interact at once. AI can generate each individual pattern. The failure usually appears in the combination.
Frontend development is becoming less about writing every line by hand and more about owning the quality of the interface.
Expect frontend roles to move in a few directions:
This does not mean every frontend developer has to become a backend engineer. It means frontend developers need enough surrounding context to make good trade-offs.
Some simple products may move closer to chat, automation, or API-first workflows. The products that still need rich interfaces will usually need better frontend engineering, not less. If the UI is where users make decisions, coordinate work, edit content, review AI output, or recover from mistakes, the interface becomes part of the product's safety and quality layer.
The core skills still matter:
The more generated code a team accepts, the more it needs engineers who can tell correct code from code that merely looks correct.
If you are choosing between roles, ask whether the company actually values frontend. A product where the browser experience is the business will give you more room to build frontend skill than a company where the UI is mostly a thin wrapper over internal data. Use the questions in How to Evaluate Companies as a Front End Engineer to separate those environments.
Yes, if you are willing to learn the browser instead of only learning a framework.
Do not start with the assumption that React alone makes you a frontend developer. React is important, but it sits on top of HTML, CSS, JavaScript, browser events, accessibility rules, network behavior, and product constraints.
A practical learning path looks like this:
Do not let tools hide gaps. If you cannot explain why generated code works, you have not learned the skill yet.
Frontend can still be a good career in 2026, but it is not an easy shortcut into software engineering.
The entry-level bar is higher than it used to be. LinkedIn's 2026 software engineering report says entry pathways are tightening, and Indeed's 2026 labor-market report shows more tech postings asking for at least five years of experience. Companies have more tooling, more AI assistance, and less patience for developers who can only assemble a screen when every requirement is spelled out.
At the same time, teams still need engineers who can make product UI reliable, accessible, fast, and maintainable.
The strongest signal you can show is not a certificate or a cloned landing page. It is working software you can explain.
Build projects that prove you can handle:
Then practice explaining your decisions. In interviews and on the job, communication is part of the work.
The risk is not using AI. The risk is having no judgment after AI gives you code.
| Replaceable signal | Strong signal |
|---|---|
| Copies generated code without reading it. | Reviews generated code and can explain every trade-off. |
| Builds only the happy path. | Handles empty, loading, error, disabled, and interrupted states. |
| Treats CSS as trial and error. | Understands layout, constraints, overflow, and responsive behavior. |
| Adds ARIA by pattern matching. | Tests keyboard behavior, focus, labels, and screen reader names. |
| Waits for exact requirements. | Clarifies scope and proposes a sensible MVP. |
| Ships one-off components. | Builds maintainable components with clear boundaries. |
| Avoids debugging. | Uses DevTools, logs, tests, and reasoning to isolate the bug. |
| Treats AI as a replacement for learning. | Treats AI as a tool for speed, exploration, and review. |
So no, frontend development is not dying in 2026. The low end is being compressed, expectations are rising, and the work that survives depends more on engineering judgment.
If you want to prepare for that version of the role, practice building real UI. Start with GreatFrontEnd's user interface coding questions, review your mistakes, and push past the version that only works in the first screenshot.

A machine coding round is a live coding interview where you build a working application or UI component from scratch in a fixed time, typically 60 to 90 minutes. In frontend interviews, the prompt is often a todo list, autocomplete, data table, image carousel, file explorer, modal dialog, or small dashboard built with HTML, CSS, JavaScript, and often React.
Companies use this round because it is hard to fake. You have to turn a rough product requirement into working code while making trade-offs in real time.
React syntax gets you through the first few minutes. The rest of the round tests whether you can break down the UI, design state, handle events, use accessible markup, keep styling readable, and still ship something that runs.
Use this as an operating guide for the round, then practice the patterns on User interface coding interview questions on GreatFrontEnd.
A machine coding round asks you to build a small but complete feature in a live coding environment. The interviewer gives you a prompt, watches how you plan, and reviews the code you write.
For a frontend role, the prompt often sounds like one of these:
The final UI does not need to look production-grade. It needs to work, and the code needs to be readable enough to discuss.
The machine coding round sits between algorithm interviews and frontend system design interviews. It is implementation-heavy.
| Round | What it tests | Typical output |
|---|---|---|
| DSA coding | Algorithms, data structures, complexity | A function that passes test cases |
| Machine coding | Feature implementation, code organization, state, UI behavior | A working component or small app |
| Frontend system design | Architecture, APIs, scalability, performance | A design discussion with diagrams and trade-offs |
| Take-home assignment | Deeper implementation without live pressure | A larger project submitted later |
That is why developers who are comfortable with DSA can still struggle here. This round is about shipping a small product, not finding one clever trick.
Your solution has to be executable, demonstrable, and easy to review. Code that looks clever but cannot be run, clicked through, or explained will not score well.
For a frontend machine coding round, aim for these deliverables:
App, the solution becomes harder to review.status value over multiple booleans when the UI has distinct modes.Machine coding rounds often end with a walkthrough. If your code works but is hard to explain, you have made the review harder than it needed to be.
A timed round is not a portfolio project. Spend the time on behavior first.
Skip these unless the prompt asks for them:
Performance and extensibility still matter, but only at the right level. In a data table question, sorting and pagination matter more than virtualizing rows before pagination works. In autocomplete, debouncing and stale-response handling matter more than a dropdown animation.
The order is simple: make the feature correct, make it readable, make it resilient, then polish.
Many machine coding resources focus on object-oriented backend-style problems: parking lots, cab booking, split expenses, inventory systems, or command-line menus. Those can teach modularity, but frontend interviews test a different surface area.
Frontend machine coding round questions care about:
For example, a generic machine coding problem might ask whether your service classes are extensible. A frontend machine coding problem might ask whether your autocomplete handles a slow response from an older request after the user has already typed a newer query. Both test design thinking, but the failure modes are different.
If your target role is frontend-heavy, practice UI problems in the browser. Reading about machine coding helps, but this round favors engineers who have built these components enough times that the implementation path feels familiar.
The usual failure mode is not lack of knowledge. It is starting to code before the solution has a shape.
If the prompt says "build autocomplete", do not immediately create an input and start fetching data. Ask what matters:
Clarification prevents building the wrong thing.
Weak solutions often put all JSX, state, event handlers, and styling in one growing component. That works for ten minutes, then becomes hard to reason about.
A better approach is to sketch the component tree before coding:
AutocompleteSearchInputSuggestionsListSuggestionItemEmptyStateErrorState
Do not over-engineer it. Separate responsibilities so the interviewer can follow the code.
State is where machine coding rounds quietly become messy. Candidates add useState calls whenever they need one more value, then discover that several states can contradict each other.
For example, this state model is fragile:
const [isLoading, setIsLoading] = useState(false);const [hasError, setHasError] = useState(false);const [results, setResults] = useState([]);const [showDropdown, setShowDropdown] = useState(false);
It is possible to end up with loading, error, and visible dropdown all at once.
For more complex UI flows, make states explicit:
const initialState = {query: '',status: 'idle', // idle | loading | success | errorresults: [],activeIndex: -1,error: null,};
You can implement that with useState, useReducer, or a small custom hook. What matters is that the states describe the UI clearly.
Interviewers notice when the happy path works but everything else breaks. Common frontend edge cases include:
You will not cover every edge case. Pick the ones that matter for the prompt and call out the rest.
In a live round, silence can make a reasonable solution look weaker than it is. Explain decisions as you go:
This makes the implementation easier to review.
In a timed round, it is tempting to keep coding until the last second. That often creates a worse outcome: the final code has a syntax error, broken import, missing prop, or state update bug that prevents the interviewer from running it.
Keep the app executable after every major step:
This rhythm feels slower, but it prevents the worst outcome: a good idea trapped inside code that does not run.
Do not wait until the final five minutes to clean up the code. If a component is becoming large, extract a small part while the mental model is still fresh. If a state variable name is confusing, rename it before more logic depends on it.
Refactoring during the round should be modest. Extract components, rename variables, move derived values into constants, and group related handlers. Avoid a full architectural rewrite unless the current code is blocking progress.
Interviewers tend to look at these areas:
A small UI component can reveal a lot about day-to-day frontend engineering ability.
Use this rubric during practice:
| Area | Weak signal | Strong signal |
|---|---|---|
| Requirements | Starts coding immediately | Clarifies MVP and follow-ups |
| Structure | One large component | Small components with clear responsibilities |
| State | Many unrelated booleans | Minimal state and derived values |
| Edge cases | Happy path only | Empty, loading, error, reset, and rapid interactions |
| Accessibility | Clickable divs everywhere | Semantic controls and keyboard-aware behavior |
| Communication | Silent implementation | Explains trade-offs while coding |
| Finish | Broken or incomplete demo | Working core feature with clear next steps |
Have a clock plan before the interview starts. Time pressure is easier when the next step is not a mystery.
Before writing code, restate the problem and choose the MVP.
For example:
"I will first build a working autocomplete with query input, loading state, fetched suggestions, and click selection. If time permits, I will add debouncing, keyboard navigation, and caching."
That sentence confirms the core behavior, limits overbuilding, and gives you a path for follow-ups.
Write a small plan in comments or on a scratchpad:
Components:- App- SearchInput- SuggestionsList- SuggestionItemState:- query- status- results- activeIndexEvents:- onChange- onSelect- onKeyDown
This gives you enough structure to start coding without drifting.
Prioritize working behavior before polish. For most React machine coding round questions, the build order should be:
For a todo list, that means add item, render list, toggle item, delete item, then filters. For autocomplete, that means input, fetch/filter, render suggestions, select item, then loading/error/keyboard support.
Do not start with animations, theme systems, or clever abstractions. Add them after the feature works.
Keep a visible "done list" in your head. After every requirement, ask whether the interviewer can verify it now. If yes, move on. If not, finish that slice before starting another feature.
Once the happy path works, add the states candidates often miss:
For accessibility-heavy components, check keyboard behavior and semantic HTML. For example, tabs should use buttons rather than clickable divs.
Use the UI like a user:
Then mention what you would improve with more time:
That turns an unfinished stretch goal into a clear trade-off.
Autocomplete is one of the best machine coding round questions because it tests state, async behavior, forms, keyboard support, accessibility, caching, and race conditions.
Before coding, split it like this:
AutocompleteSearchInputSuggestionsListEmptyStateErrorState
Then define the state transitions:
| User action | State change |
|---|---|
| Types query | Update query, set status to loading |
| API succeeds | Store results, set status to success |
| API fails | Store error, set status to error |
| Selects result | Set query, close suggestions |
| Clears input | Reset to idle |
You might start with this shape:
function Autocomplete() {const [query, setQuery] = useState('');const [status, setStatus] = useState('idle');const [results, setResults] = useState([]);const hasResults = status === 'success' && results.length > 0;const showEmptyState = status === 'success' && results.length === 0;return (<div><label htmlFor="search">Search</label><inputid="search"value={query}onChange={(event) => setQuery(event.target.value)}/>{status === 'loading' && <p>Loading...</p>}{showEmptyState && <p>No results found.</p>}{hasResults && (<ul>{results.map((item) => (<li key={item.id}>{item.label}</li>))}</ul>)}</div>);}
This is the skeleton, not the final solution. Once it works, add debouncing, request cancellation, keyboard navigation, caching, highlighted matches, and accessibility improvements.
Sequence matters. Build the smallest correct version, then layer complexity.
Once the skeleton works, upgrade it in this order:
The stale response bug shows up often. Suppose the user types rea, then quickly types react. If the rea request returns after the react request, a naive implementation can show the wrong results.
One simple defense is to track the latest query inside the effect:
useEffect(() => {if (query.trim() === '') {setStatus('idle');setResults([]);return;}let ignore = false;setStatus('loading');fetchResults(query).then((items) => {if (!ignore) {setResults(items);setStatus('success');}}).catch((error) => {if (!ignore) {setError(error);setStatus('error');}});return () => {ignore = true;};}, [query]);
This is not the only fix. It does show that you understand the browser reality: users type quickly, networks are unpredictable, and UI state must not be overwritten by stale async work.
If time is short, avoid random practice. Focus on patterns that repeat across many rounds.
Start with questions that force you to manage local state cleanly:
Start here because the requirements are small and the component-design lessons repeat everywhere.
Then move to questions involving fetched data, sorting, filtering, pagination, and loading states:
These questions feel closer to everyday product work.
Finally, practice questions with more moving parts:
These expose gaps in event handling, timers, focus management, and state transitions.
For a broader list, use 50 React coding interview questions with solutions and prioritize the ones that match your target roles.
Practice only works when you review the attempt honestly. After solving a question on GreatFrontEnd, compare your solution with the official solution and ask:
Keep a small mistake log. When three attempts show the same issue, that is your next focus area. If your components repeatedly become too large, practice extracting presentational subcomponents. If async bugs keep appearing, practice debouncing, cleanup functions, request cancellation, and loading/error states.
Machine coding round preparation should look like deliberate repetition, not passive reading.
Pick simple components and implement them without looking at solutions. Focus on:
Good questions for this stage: todo list, tabs, accordion, contact form, progress bar, and modal.
Move into data tables, job boards, autocomplete-style flows, and file explorers. Focus on:
This is where frontend machine coding round questions start to feel realistic.
Use a timer. Give yourself 60 minutes for medium questions and 90 minutes for harder ones.
After each attempt, review:
As you practice, explain your approach out loud. Interviewers are evaluating code and judgment.
Follow-ups are where interviewers test whether your implementation is extensible. After completing a question, add one extra requirement:
You are not trying to memorize every feature. You are checking whether your original structure makes follow-ups easy. If adding one small requirement forces a rewrite, the initial design was probably too rigid.
Before your next machine coding round, remember this:
When you feel stuck, return to the MVP. A small working solution beats an ambitious broken one.
Frontend LLD focuses on component APIs, state ownership, extensibility, and interaction contracts. A machine coding round asks you to implement the component or app live. The two overlap, but machine coding is more implementation-heavy.
No. Frontend machine coding round questions can be solved with vanilla JavaScript, React, Vue, Angular, or another framework. For React roles, practice in React because the interviewer will expect component-driven thinking and hook-based state management.
Practice fewer questions more deeply. Ten well-reviewed questions are better than fifty shallow attempts. A strong base includes todo list, tabs, accordion, modal, data table, file explorer, job board, progress bars, image carousel, and one autocomplete-style problem.
Use a platform where you can write code, run it, compare with solutions, and practice realistic UI prompts. Start with React interview questions on GreatFrontEnd, then move into specific user interface coding questions.
The machine coding round is an execution test. You do not need a perfect production app in 90 minutes. You need to understand the requirements, break down the UI, design state, implement the core behavior, handle the right edge cases, and communicate trade-offs.
That is trainable. Pick one question, set a timer, build the MVP, review your mistakes, and repeat. The round gets easier once your process is stronger than the pressure of the clock.

As Front End Engineers, we aim to deliver the best user experience and one of the ways to achieve that is by optimizing the applications' performance.
Users expect fast, responsive experiences, and will quickly abandon sites that are slow to load. Google's research found that 53% of mobile users abandon a page that takes more than 3 seconds to load. With the prevalent usage of mobile devices which can be on slower network speeds, optimizing performance is critical.
Code splitting and lazy loading are effective strategies to achieve great performance on the web. In this post, we’ll explore these techniques, their benefits, and how they can be implemented in React.
Code splitting breaks down your application into smaller chunks, loading only the necessary parts to reduce the bundle size. Lazy loading defers loading non-essential resources until they’re needed, further enhancing performance.
For example, consider a React app with a Login, Dashboard, and Listing page. Traditionally, the code for all these pages are bundled in a single JS file. This is suboptimal because when the user visits the Login page, it is unnecessary to load pages such as the Dashboard and Listing page. But with implementing code splitting and lazy loading, we can dynamically load specific components/pages only when needed, significantly improving performance.
In React, code splitting can be introduced via dynamic import(). Dynamic import is a built-in way to do this in JavaScript. The syntax looks like this:
import('./math').then((math) => {console.log(math.add(1, 2));});
For React apps, code splitting via dynamic imports works out of the box with modern toolchains like Vite, Next.js, and React Router. The React.lazy() function (introduced in React 16.6) lets you render a dynamic import as a regular component, splitting a large JS bundle into smaller chunks that load on demand.
If you're on a custom Webpack setup, refer to the Webpack guide for configuring code splitting.
To implement lazy loading in React, we can leverage React.lazy function and the Suspense component to handle loading states. Here's an example demonstrating lazy loading in React:
const LazyComponent = React.lazy(() => import('./LazyComponent'));function App() {return (<React.Suspense fallback={<div>Loading...</div>}><LazyComponent /></React.Suspense>);}
By wrapping a lazy-loaded component with Suspense, we can provide a fallback/placeholder UI while the component is being loaded asynchronously, such as a spinner.
However, there can be a case where LazyComponent fails to load due to some reason like network failure. In that case, it needs to handle the error smoothly for a better user experience with Error Boundaries.
import MyErrorBoundary from './MyErrorBoundary';const LazyComponent = React.lazy(() => import('./LazyComponent'));function App() {return (<MyErrorBoundary><React.Suspense fallback={<div>Loading...</div>}><LazyComponent /></React.Suspense></MyErrorBoundary>);}
So, when the LazyComponent is lazily loaded, it signifies that the code for LazyComponent is segmented into a distinct JS chunk, separate from the main JS bundle. This JS chunk is exclusively loaded when the LazyComponent is required to be displayed on the user interface, optimizing the loading process and enhancing the application's performance.
Note: Since React 18, React.lazy and Suspense work on the server too via streaming SSR APIs (renderToPipeableStream for Node.js, renderToReadableStream for Edge). Frameworks like Next.js handle this for you. The third-party @loadable/component library was the pre-React-18 workaround and is rarely needed today.
From the above, we have seen how we use React.lazy to code split and lazy load components. But the question is where to lazy load and code split. There are approaches like Route-based code splitting and Component-based code splitting.

Route-based code splitting is almost always the best place to start. It typically gives the largest reduction in initial JS, since each route ends up as its own chunk and only the active one is loaded. Modern bundlers (Webpack 5, Vite/Rollup, Turbopack) automatically extract shared dependencies into common chunks, so you don't usually have to worry about duplication across routes. Just check your build output occasionally to confirm shared code lives in vendor chunks rather than being inlined into every route bundle.
Here is an example of route-based code splitting:
import { Suspense, lazy } from 'react';import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';const Login = lazy(() => import('./Login'));const Dashboard = lazy(() => import('./Dashboard'));const App = () => (<Router><Suspense fallback={<div>Loading...</div>}><Routes><Route path="/" element={<Login />} /><Route path="/dashboard" element={<Dashboard />} /></Routes></Suspense></Router>);

Component-based code splitting provides granular control over loading specific components, allowing for more precise optimization. The real power of code splitting comes into the picture in component-based code splitting where we have more control over granular components. When deciding which components to lazy load, consider the importance and impact of each component on the initial rendering and user experience. Ideal candidates for lazy loading are large components with significant code or resources, conditional components that are not always needed, and secondary or non-essential features. These can be segmented into separate chunks and loaded on demand, optimizing performance. However, critical components like headers, main content, and dependencies should be loaded upfront to ensure a seamless user experience. We need to be careful in selecting which components to lazy load to strike a balance between initial load times and providing essential functionality. Here is an example of component-based code splitting:
import { useState, lazy, Suspense } from 'react';const Modal = lazy(() => import('./Modal'));function App() {const [showModal, setShowModal] = useState(false);const openModal = () => {setShowModal(true);};const closeModal = () => {setShowModal(false);};return (<div><button onClick={openModal}>Open Modal</button>{showModal && (<Suspense fallback={<div>Loading Modal...</div>}><Modal onClose={closeModal} /></Suspense>)}</div>);}export default App;
In this example, the Modal component is lazily loaded using React.lazy() and dynamically imported. The modal is conditionally rendered based on the showModal state, which is toggled by the openModal and closeModal functions. The Suspense component displays a loading indicator while the modal component is being loaded asynchronously. This implementation optimizes performance by loading the modal component only when the user interacts with the Open Modal button, preventing unnecessary loading of heavy components like a text editor until they are actually needed.
If you’re using Webpack to bundle your application, then you can use Webpack's magic comments to further improve the user experience with lazy loading.
We can use webpackPrefetch and webpackPreload for dynamic imports. In the above example of the lazy loading Modal, the Modal is loaded only when the user clicks the Open Modal button and the user has to wait for a fraction of a second to load the Modal.
We can improve the user experience by not making users wait for the Modal to load. So, in that scenario, we can prefetch or preload the Modal component. In the above example of the Lazy loading modal, the only difference will be in how we import the Modal component.
Before:
const Modal = lazy(() => import('./Modal'));
After:
const Modal = lazy(() => import(/* webpackPrefetch: true */ './Modal'));
What webpackPrefetch: true does is that it tells the browser to automatically load this component into the browser cache so it's ready ahead of time and the user won’t have to wait for the Modal component to load when the user clicks on the Open Modal button.
We can use webpackPrefetch and webpackPreload for a particular component when we think that there is a high possibility for the user to use that component when a user visits the app.
Note that magic comments are Webpack-specific. Vite (Rollup) and Turbopack don't honor them. If you're on Next.js, route chunks are prefetched automatically by <Link>, but next/dynamic itself has no prefetch option, so for high-probability interactions you typically trigger the dynamic import() yourself on hover or focus. On Vite, you can use <link rel="prefetch"> directly or a plugin like vite-plugin-preload.
React.lazyFor a long time, Suspense was mostly known as the fallback for React.lazy. Two newer features extend what it can do: streaming SSR (added in React 18) and the use() hook (added in React 19). Both work with the same Suspense boundaries you already place for lazy loading, so a single boundary can show a fallback while a chunk downloads, while data resolves, and while the server streams the rest of the tree.
use() hook with SuspenseThe use() hook lets a component unwrap a promise (or read context). React suspends the component until the promise resolves, so you don't need a useEffect or a manual loading state. It works in both server and client components, but the most common pattern is unwrapping a promise in a client component.
'use client';import { use, Suspense } from 'react';import ErrorBoundary from './ErrorBoundary';function Profile({ userPromise }) {// React suspends here until userPromise resolves.const user = use(userPromise);return <h1>Hello, {user.name}</h1>;}export default function ProfilePage({ userPromise }) {return (<ErrorBoundary fallback={<p>Failed to load profile</p>}><Suspense fallback={<p>Loading...</p>}><Profile userPromise={userPromise} /></Suspense></ErrorBoundary>);}
The typical pattern is to start the fetch in a server component (or route loader), pass the unresolved promise down to a client component, and let use() handle the suspending. The request is in-flight before the client component renders, so the user sees the resolved UI sooner than if the client had to fetch on mount.
Streaming SSR with Suspense has been available since React 18, via renderToPipeableStream (Node.js) or renderToReadableStream (Edge). When a Suspense boundary suspends on the server, the server doesn't block. It sends the fallback HTML immediately and streams the resolved content as soon as it's ready. This is how Next.js App Router's loading.tsx works.
For code splitting, a route-level Suspense boundary lets the server flush the shell, navigation, and skeleton early, then stream in the lazy-loaded sections as their chunks resolve. First Contentful Paint (FCP) usually improves as a result.
React.lazyReact Server Components (RSC) change which components even need code splitting. Server Components run only on the server and are never sent as JavaScript to the browser, so they don't add to the client bundle. You can't (and shouldn't) wrap them in React.lazy.
A short reference for what to split:
| Component type | Ships JS to browser? | Use React.lazy? |
|---|---|---|
| Server Component (default in App Router) | No | No, it's already not in the bundle |
Client Component ('use client') used everywhere | Yes | Optional, split when it's heavy or below-the-fold |
| Client Component used conditionally (modal, chart, editor) | Yes | Yes, high-impact split |
| Route component | Yes (the route's bundle) | The router handles this for you in App Router |
The Next.js App Router does route-based splitting automatically. Every page.tsx is its own bundle, so you only need explicit React.lazy (or next/dynamic) for client components that are heavy and not always rendered: rich-text editors, charting libraries, video players, or feature-flag-gated UI.
The rule of thumb for modern React apps: default to Server Components to keep work off the client, and use React.lazy or next/dynamic for heavy client components that render conditionally.
It depends on the initial bundle size and how much of it is unused on first paint. A few useful reference points:
Three metrics to measure before and after a split:
web-vitals library or the Chrome User Experience Report.If none of them move, the split isn't worth the complexity.
When asked "how would you optimize bundle size in a React app?", these are the mistakes that come up most often:
React.lazy for Server Components. In the App Router, Server Components aren't in the client bundle. Wrapping one in React.lazy or next/dynamic is a no-op at best and an error at worst. Use splitting only for client components with significant code.import() as instant. A lazy import is a network request. If the user clicks "Open editor" and waits 800 ms on a spinner, lazy loading has made things worse. Combine it with prefetching (webpackPrefetch on Webpack, or triggering the dynamic import() on hover/focus on other bundlers) for high-probability interactions.Be sure to assess your application's requirements, tech stack and challenges when deciding the code splitting and lazy loading approach. By strategically dividing code and loading resources on demand, you can create fast, efficient, and engaging web applications.
To strengthen your React fundamentals further, check out our Top ReactJS Interview Questions GitHub repo - a curated collection of 50 frequently asked questions from real interview scenarios.

Headless UI libraries handle the logic, accessibility, and interaction behavior of UI components but leave the styling to you. You bring your own styles or design system, and the library handles keyboard navigation, focus management, ARIA semantics, RTL support, and controlled vs uncontrolled state.
A couple of things have shifted since 2024:
The libraries below are ordered by npm weekly downloads, with shadcn/ui covered last.
These libraries don't all sit at the same layer of your stack:
Picking shadcn/ui doesn't mean skipping the primitive layer. Radix UI (or Base UI, since 2025) still lives in your node_modules underneath your components/ui/ folder. Picking React Aria means writing more code per component, but it gives you the deepest accessibility primitives available.

Headless UI is built by the Tailwind CSS team. It's a small set of unstyled, accessible components designed to compose with Tailwind utilities. The component count is intentionally small (~10 components) and the API is the most beginner-friendly in this list.
By the numbers (as of May 2026):
@headlessui/react): ~5.49MBest for: Tailwind-first teams that want a familiar, opinionated API and don't need the composability of Radix-style primitives.
Skip if: You need components beyond what's covered (no Combobox-with-virtualization, no advanced data table primitives), or you want more composability. Radix and Base UI both expose more primitives.

React Aria by Adobe is the most accessibility-rigorous option in this list. It's a library of React Hooks (rather than components) that handle behavior, ARIA semantics, internationalization, and adaptive interactions across 40+ component patterns.
You compose hooks (useButton, useDialog, useTabs) into your own components, which means more code per component but more control over the rendered output. Worth the investment when accessibility is a hard requirement.
By the numbers (as of May 2026):
react-aria): ~4.47MBest for: Government, enterprise, or any product where WAI-ARIA conformance is contractually required. Also when you need internationalization (RTL, locale-aware date/number components) out of the box.
Skip if: You're shipping a v0 product and want pre-built components. React Aria's hooks-first model is more verbose than Radix or Base UI.

Radix UI is the original primitive library that popularized headless components in React. It provides 30+ unstyled, accessible components (Dialog, Dropdown, Tabs, Popover, etc.) with full keyboard navigation, focus management, ARIA, and RTL support built in.
Radix UI was acquired by WorkOS, and update velocity has slowed for some complex components (Combobox and multi-select being the ones commonly cited). The primitives still see heavy usage through shadcn/ui. @radix-ui/react-slot alone pulls ~131M weekly npm downloads as of mid-2026.
By the numbers (as of May 2026):
Best for: When you want pre-built accessible primitives without the copy-paste of shadcn/ui, and you already have your own styling solution (CSS Modules, Emotion, vanilla CSS, etc.).
Skip if: You need brand-new primitives that haven't shipped yet. Base UI is iterating faster on those.

Base UI is the actively maintained alternative to Radix for the primitive layer. Maintained by MUI with full-time engineers, it provides similar headless primitives with a slightly different API.
shadcn/ui added Base UI as a supported primitive layer in 2025, so you can now choose between Radix-backed and Base UI-backed shadcn components.
By the numbers (as of May 2026):
@base-ui/react): ~3.7MBest for: Greenfield projects where you want the most actively maintained primitive layer, or anyone who hit Radix limitations on a complex component (Combobox, multi-select).
Skip if: You're already deep in a Radix codebase and migration cost is high. Radix still works, it just isn't moving as fast.

Aria Kit is an open-source library of unstyled, primitive components and hooks for accessible web apps. It ships smaller bundles than most for what you get, with an API that sits between Radix's component composition and React Aria's hooks-first style.
By the numbers (as of May 2026):
@ariakit/react): ~697.9kBest for: When bundle size matters more than ecosystem familiarity. Often picked by component library authors building their own libraries on top of a primitive layer.
Skip if: You want the largest community and Stack Overflow surface area. Aria Kit is smaller than Radix and React Aria.

Ark UI is unique in this list: same headless primitive philosophy, but the components work across React, Vue, and Solid. The internal logic is built with state machines (XState) for predictable behavior on complex components.
By the numbers (as of May 2026):
@ark-ui/react): ~634.7kBest for: Multi-framework design systems where you need the same Combobox behavior in a React app and a Vue app and want to maintain one logic implementation.
Skip if: You're React-only. The React-specific options above usually have more idiomatic React APIs.

shadcn/ui isn't strictly a headless library since its components ship with Tailwind styles applied. We're including it because it's how most teams now consume Radix or Base UI primitives in production.
It's a CLI that copies pre-built component source code into your project. The components are built on Radix UI primitives by default (with Base UI as an opt-in alternative since 2025) and styled with Tailwind CSS.
The mental model is different from a typical npm package:
npm install shadcn-ui and import components.npx shadcn add button and the source code for the Button component is added to your repo at components/ui/button.tsx.You trade dependency management for full control over the code, including the option to strip the Tailwind classes and treat the underlying Radix or Base UI layer as truly headless. That trade-off is why it has taken over so much of the React UI ecosystem.
By the numbers (as of May 2026):
Best for: New product apps where you want full design control on top of headless primitives without writing accessibility logic from scratch, especially if you're already using Tailwind.
Skip if: You can't use Tailwind, want a strictly headless library, or want a published library you can npm update (you don't get that with shadcn/ui).

Any of the libraries above can be used to ship an accessible, maintainable app. Pick the one that matches your styling preferences and how much code you're willing to write per component.
Want to solidify your React foundation while exploring UI libraries like these? Check out our Top ReactJS Interview Questions GitHub repo with 50 frequently asked questions to help you prepare for projects and interviews.

Modern CSS interviews test your ability to solve real problems, not recite definitions. You'll debug broken layouts, explain why a sticky navbar fails on mobile Safari, choose between Flexbox and Grid for specific use cases, and demonstrate knowledge of features like Container Queries and the :has() selector.
But here's what separates strong candidates from average ones: it's not just what you know, it's how you think. Interviewers want to see your problem-solving process, your ability to articulate trade-offs, and your understanding of "why" certain approaches work better than others. A candidate who can explain when to use em vs rem and justify their choice is far more valuable than someone who's memorized every CSS property.
This post focuses on:
Whether you're preparing for your first frontend role or interviewing at a senior level, this post will help you demonstrate both technical depth and clear reasoning - exactly what interviewers look for.
The box model is the foundation of CSS layout. Every element is a rectangular box with four areas: content, padding, border, and margin.
The interview question: "Explain the CSS box model and the difference between box-sizing: content-box and box-sizing: border-box".
/* content-box (default) */.content-box {box-sizing: content-box;width: 200px;padding: 20px;border: 5px solid black;/* Total width = 200 + 40 (padding) + 10 (border) = 250px */}/* border-box (modern approach) */.border-box {box-sizing: border-box;width: 200px;padding: 20px;border: 5px solid black;/* Total width = 200px (padding and border included) */}
Key points:
content-box adds padding and border to the specified widthborder-box includes padding and border within the specified widthbox-sizing: border-box globallybox-sizingPro tip: Explain that border-box makes responsive layouts more predictable because percentage widths behave intuitively.
The display property controls how an element participates in layout flow.
Common interview question: "What's the difference between display: none, visibility: hidden, and opacity: 0?"
| Property | Space Occupied | Accessible to Screen Readers | Events Triggered | Use Case |
|---|---|---|---|---|
display: none | No | No | No | Completely remove from layout |
visibility: hidden | Yes | No | No | Hide but maintain layout space |
opacity: 0 | Yes | Yes | Yes | Fade animations, accessible hiding |
Key display values:
/* Block - takes full width, stacks vertically */.block {display: block;}/* Inline - flows with text, respects horizontal spacing only */.inline {display: inline;}/* Inline-block - flows with text but respects width/height */.inline-block {display: inline-block;width: 100px;height: 100px;}/* Flex - modern one-dimensional layout */.flex {display: flex;}/* Grid - modern two-dimensional layout */.grid {display: grid;}
CSS Custom Properties (variables) enable dynamic, maintainable stylesheets.
Interview question: "How do CSS variables work, and what are their advantages over preprocessor variables?"
/* Define variables in :root for global scope */:root {--primary-color: #007bff;--spacing-unit: 8px;--border-radius: 4px;}/* Use variables with var() */.button {background-color: var(--primary-color);padding: calc(var(--spacing-unit) * 2);border-radius: var(--border-radius);}/* Override in specific contexts */.dark-theme {--primary-color: #66b3ff;}/* Fallback values */.element {color: var(--text-color, #333);}
CSS variables vs preprocessor variables:
| Feature | CSS Variables | Sass/Less Variables |
|---|---|---|
| Runtime changes | ✅ Yes | ❌ No (compile-time only) |
| JavaScript access | ✅ Yes | ❌ No |
| Cascade & inheritance | ✅ Yes | ❌ No |
| Browser support | ✅ Modern browsers | ✅ Compiles to CSS |
JavaScript integration:
// Read CSS variableconst primary = getComputedStyle(document.documentElement).getPropertyValue('--primary-color',);// Set CSS variabledocument.documentElement.style.setProperty('--primary-color', '#ff0000');
Specificity determines which CSS rule applies when multiple rules target the same element.
The classic question: "Explain CSS specificity. How is it calculated?"
Specificity hierarchy:
/* Specificity: 0-0-0-1 (1 element) */p {color: black;}/* Specificity: 0-0-1-0 (1 class) */.text {color: blue;}/* Specificity: 0-0-1-1 (1 class + 1 element) */p.text {color: green;}/* Specificity: 0-1-0-0 (1 ID) */#header {color: red;}/* Specificity: 1-0-0-0 (inline style) */<p style="color: purple;">/* Specificity: ∞ (!important overrides everything) */p {color: orange !important;}
Specificity calculation:
Example problem:
/* Which color wins? */#nav .menu li {color: red;} /* 0-1-1-1 = 111 */.header .menu li {color: blue;} /* 0-0-2-1 = 021 */li.active {color: green;} /* 0-0-1-1 = 011 *//* Answer: red (highest specificity) */
The position property controls how elements are positioned in the document flow.
Interview question: "Explain the different position values and when to use each".
/* Static (default) - normal document flow */.static {position: static;}/* Relative - offset from normal position, space preserved */.relative {position: relative;top: 10px;left: 20px;}/* Absolute - positioned relative to nearest positioned ancestor */.absolute {position: absolute;top: 0;right: 0;}/* Fixed - positioned relative to viewport */.fixed {position: fixed;bottom: 20px;right: 20px;}/* Sticky - hybrid of relative and fixed */.sticky {position: sticky;top: 0;}
Common use cases:
| Position | Use Case | Example |
|---|---|---|
static | Default flow | Regular content |
relative | Minor adjustments, positioning context | Offset badges, anchor for absolute children |
absolute | Overlays, tooltips | Dropdown menus, modals |
fixed | Persistent UI | Navigation bars, chat widgets |
sticky | Scroll-aware headers | Table headers, section titles |
Critical concept - positioning context:
/* Absolute positioning requires a positioned parent */.parent {position: relative; /* Creates positioning context */}.child {position: absolute;top: 0; /* Relative to .parent, not viewport */left: 0;}
Stacking context determines the 3D layering of elements along the z-axis.
Advanced interview question: "What creates a stacking context, and how does z-index work?"
What creates a stacking context:
/* 1. Root element (html) *//* 2. Positioned elements with z-index */.positioned {position: relative;z-index: 10;}/* 3. Flex/Grid items with z-index */.flex-item {z-index: 5;}/* 4. Elements with opacity < 1 */.transparent {opacity: 0.9;}/* 5. Transform, filter, perspective */.transformed {transform: translateZ(0);}/* 6. will-change */.optimized {will-change: transform;}
Z-index rules:
/* z-index only works on positioned elements */.static {z-index: 999; /* ❌ No effect (position: static) */}.relative {position: relative;z-index: 999; /* ✅ Works */}/* z-index is scoped to stacking context */.parent {position: relative;z-index: 1;}.child {position: relative;z-index: 9999; /* Still behind elements with z-index: 2 in different context */}
What to explain:
z-index only works on positioned elements (except flex/grid children)opacity, transform, filter, position + z-indexPseudo-classes select elements based on state, while pseudo-elements style specific parts of elements.
Interview question: "What's the difference between pseudo-classes and pseudo-elements?"
Pseudo-classes:
/* User interaction */a:hover {color: blue;}input:focus {border-color: blue;}button:active {transform: scale(0.98);}/* Form states */input:disabled {opacity: 0.5;}input:checked + label {font-weight: bold;}input:valid {border-color: green;}input:invalid {border-color: red;}/* Structural */li:first-child {margin-top: 0;}li:last-child {margin-bottom: 0;}li:nth-child(odd) {background: #f0f0f0;}li:nth-child(3n) {/* Every 3rd item */}
Pseudo-elements:
/* Generated content */.icon::before {content: '→';margin-right: 8px;}.external-link::after {content: ' ↗';}/* Text styling */p::first-line {font-weight: bold;}p::first-letter {font-size: 2em;float: left;}/* Selection styling */::selection {background: yellow;color: black;}
Key differences:
| Pseudo-classes | Pseudo-elements |
|---|---|
| Select elements in a specific state | Style specific parts of elements |
Single colon : (or ::) | Double colon :: |
:hover, :focus, :nth-child() | ::before, ::after, ::first-line |
CSS units determine how sizes are calculated. Choosing the right unit is crucial for responsive design.
Interview question: "Explain the difference between px, em, rem, %, and viewport units. When should you use each?"
/* Absolute - fixed size */.pixel {font-size: 16px; /* Always 16 pixels */}/* Relative to parent font-size */.em-unit {font-size: 1.5em; /* 1.5 × parent font-size */padding: 1em; /* 1 × this element's font-size */}/* Relative to root font-size */.rem-unit {font-size: 1.5rem; /* 1.5 × root font-size (usually 16px) */padding: 1rem; /* Always consistent */}/* Relative to parent dimensions */.percentage {width: 50%; /* 50% of parent width */}/* Relative to viewport */.viewport {width: 100vw; /* 100% of viewport width */height: 100vh; /* 100% of viewport height */}
Em vs rem - the compounding problem:
/* Em compounds */.parent {font-size: 16px;}.child {font-size: 1.5em; /* 16 × 1.5 = 24px */}.grandchild {font-size: 1.5em; /* 24 × 1.5 = 36px (compounds!) */}/* Rem doesn't compound */.parent {font-size: 1.5rem; /* 24px */}.child {font-size: 1.5rem; /* Still 24px (relative to root) */}
When to use each unit:
| Unit | Best For | Example |
|---|---|---|
px | Borders, shadows, precise control | border: 1px solid |
em | Spacing relative to font-size | padding: 0.5em 1em |
rem | Font sizes, consistent spacing | font-size: 1.125rem |
% | Responsive widths, fluid layouts | width: 50% |
vw/vh | Full-screen sections, responsive typography | height: 100vh |
Flexbox is a one-dimensional layout system for distributing space along a single axis.
Core interview question: "Explain Flexbox and its main properties".
Flex container properties:
.container {display: flex;/* Main axis direction */flex-direction: row; /* row | row-reverse | column | column-reverse *//* Wrapping */flex-wrap: wrap; /* nowrap | wrap | wrap-reverse *//* Main axis alignment */justify-content: space-between; /* flex-start | flex-end | center | space-between | space-around | space-evenly *//* Cross axis alignment */align-items: center; /* flex-start | flex-end | center | baseline | stretch *//* Gap between items */gap: 16px;}
Flex item properties:
.item {/* Growth factor */flex-grow: 1; /* Default: 0 *//* Shrink factor */flex-shrink: 1; /* Default: 1 *//* Base size */flex-basis: 200px; /* Default: auto *//* Shorthand: grow shrink basis */flex: 1 1 200px;flex: 1; /* Same as: 1 1 0 *//* Individual alignment */align-self: flex-end;}
Common patterns:
/* Equal-width columns */.column {flex: 1;}/* Center content */.center {display: flex;justify-content: center;align-items: center;}/* Space between header and footer */.layout {display: flex;flex-direction: column;min-height: 100vh;}.content {flex: 1; /* Takes remaining space */}
CSS Grid is a two-dimensional layout system for rows and columns.
Interview question: "When would you use Grid over Flexbox?"
Grid container properties:
.grid {display: grid;/* Define columns */grid-template-columns: 200px 1fr 1fr; /* Fixed + flexible */grid-template-columns: repeat(3, 1fr); /* 3 equal columns */grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* Responsive *//* Define rows */grid-template-rows: 100px auto 100px;/* Gap */gap: 20px;/* Alignment */justify-items: center; /* Align items horizontally */align-items: center; /* Align items vertically */}
Grid item properties:
.item {/* Column placement */grid-column: 1 / 3; /* Start at line 1, end at line 3 */grid-column: span 2; /* Span 2 columns *//* Row placement */grid-row: 1 / 3;grid-row: span 2;}
Named grid areas:
.layout {display: grid;grid-template-areas:'header header header''sidebar content content''footer footer footer';grid-template-columns: 200px 1fr 1fr;}.header {grid-area: header;}.sidebar {grid-area: sidebar;}.content {grid-area: content;}.footer {grid-area: footer;}
Interview question: "How do you decide between Flexbox and Grid?"
Use Flexbox for:
Use Grid for:
They work together:
/* Grid for page layout */.page {display: grid;grid-template-columns: 250px 1fr;}/* Flexbox for navigation inside header */.header nav {display: flex;justify-content: space-between;align-items: center;}/* Grid for card layout */.cards {display: grid;grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));gap: 2rem;}/* Flexbox inside each card */.card {display: flex;flex-direction: column;}.card-content {flex: 1;}
The classic interview question: "How do you center a div?"
Modern solutions:
/* 1. Flexbox (most common) */.flex-center {display: flex;justify-content: center;align-items: center;}/* 2. Grid */.grid-center {display: grid;place-items: center; /* Shorthand for align-items + justify-items */}/* 3. Absolute positioning */.absolute-center {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);}/* 4. Margin auto (horizontal only) */.margin-center {width: 300px;margin: 0 auto;}
When to use each:
| Method | Use Case | Pros | Cons |
|---|---|---|---|
| Flexbox | Most situations | Simple, flexible | Requires parent styling |
| Grid | Grid layouts | Very concise | Overkill for simple cases |
| Absolute + Transform | Overlays, modals | Works without knowing size | Removes from flow |
| Margin auto | Block elements | Simple for horizontal | Vertical requires height |
Media queries enable responsive designs that adapt to different screen sizes and device capabilities.
Interview question: "Explain mobile-first vs desktop-first approaches to responsive design".
Mobile-first approach (recommended):
/* Base styles for mobile */.container {padding: 1rem;font-size: 14px;}/* Tablet and up */@media (min-width: 768px) {.container {padding: 2rem;font-size: 16px;}}/* Desktop and up */@media (min-width: 1024px) {.container {padding: 3rem;max-width: 1200px;margin: 0 auto;}}
Beyond width - other media features:
/* Orientation */@media (orientation: landscape) {.gallery {grid-template-columns: repeat(4, 1fr);}}/* Hover capability (desktop vs touch) */@media (hover: hover) {.button:hover {background: blue;}}@media (hover: none) {.button:active {background: blue;}}/* Prefers color scheme */@media (prefers-color-scheme: dark) {:root {--bg-color: #1a1a1a;--text-color: #ffffff;}}/* Prefers reduced motion */@media (prefers-reduced-motion: reduce) {* {animation-duration: 0.01ms !important;transition-duration: 0.01ms !important;}}
What interviewers want to hear:
prefers-reduced-motionTransforms change an element's appearance without affecting document flow. Transitions animate property changes.
Interview question: "Explain the difference between transforms and transitions. How do they affect performance?"
Transforms:
/* 2D Transforms */.transform-2d {transform: translate(50px, 100px);transform: rotate(45deg);transform: scale(1.5);transform: translate(50px, 100px) rotate(45deg) scale(1.2);}/* 3D Transforms */.transform-3d {transform: translateZ(100px);transform: rotateY(45deg);transform: perspective(1000px) rotateY(45deg);}
Transitions:
/* Basic transition */.button {background: blue;transition: background 0.3s ease;}.button:hover {background: darkblue;}/* Multiple properties */.card {transform: scale(1);box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);transition:transform 0.3s ease,box-shadow 0.3s ease;}.card:hover {transform: scale(1.05);box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);}
Performance considerations:
/* ✅ GPU-accelerated (performant) */.performant {transform: translateX(100px);opacity: 0.5;}/* ❌ Triggers layout/paint (slow) */.slow {left: 100px; /* Use transform instead */width: 200px; /* Triggers reflow */}
What to emphasize:
transform and opacity are GPU-acceleratedwidth, height, top, left - use transform insteadwill-change hints to browser but use sparingly (memory cost)Responsive images adapt to different screen sizes and resolutions for optimal performance.
CSS approaches:
/* Basic responsive image */img {max-width: 100%;height: auto;}/* Object-fit for aspect ratio control */.image-container {width: 300px;height: 200px;}.image-container img {width: 100%;height: 100%;object-fit: cover; /* cover | contain | fill */object-position: center;}
HTML approaches:
<!-- srcset for different resolutions --><imgsrc="image.jpg"srcset="image.jpg 1x, image@2x.jpg 2x, image@3x.jpg 3x"alt="Description" /><!-- picture element for art direction --><picture><source media="(min-width: 1024px)" srcset="desktop.jpg" /><source media="(min-width: 768px)" srcset="tablet.jpg" /><img src="mobile.jpg" alt="Description" /></picture><!-- Modern formats with fallback --><picture><source srcset="image.avif" type="image/avif" /><source srcset="image.webp" type="image/webp" /><img src="image.jpg" alt="Description" /></picture>
Aspect ratio (modern CSS):
/* New way - aspect-ratio property */.aspect-ratio-new {aspect-ratio: 16 / 9;}.aspect-ratio-new img {width: 100%;height: 100%;object-fit: cover;}
Modern CSS functions enable responsive values without media queries.
Interview question: "Explain how clamp(), min(), and max() work and when to use them".
/* min() - picks the smallest value */.element {width: min(100%, 600px); /* Never wider than 600px */}/* max() - picks the largest value */.element {width: max(50%, 300px); /* At least 300px wide */}/* clamp() - value between min and max */.element {/* clamp(minimum, preferred, maximum) */font-size: clamp(1rem, 2.5vw, 2rem);/* Font size is 2.5vw, but never smaller than 1rem or larger than 2rem */}
Practical examples:
/* Responsive typography without media queries */h1 {font-size: clamp(2rem, 5vw, 4rem);}/* Responsive container width */.content {width: min(90%, 1200px);margin: 0 auto;}/* Responsive spacing */.container {padding: clamp(1rem, 5vw, 3rem);}
Container queries allow components to respond to their container size, not the viewport.
Interview question: "What are container queries and how do they differ from media queries?"
/* Define a container */.card-container {container-type: inline-size;container-name: card;}/* Query the container */@container card (min-width: 400px) {.card {display: grid;grid-template-columns: 200px 1fr;}}@container card (min-width: 600px) {.card {grid-template-columns: 250px 1fr;font-size: 1.125rem;}}
Why container queries matter:
:has() parent selectorThe :has() pseudo-class selects parent elements based on their children.
Interview question: "What is the :has() selector and what problems does it solve?"
/* Select parent that contains specific child */.card:has(img) {display: grid;grid-template-columns: 200px 1fr;}/* Select parent based on child state */form:has(input:invalid) {border: 2px solid red;}/* Style parent when checkbox is checked */.option:has(input:checked) {background: blue;color: white;}
Form validation styling:
/* Show error when input is invalid and touched */.form-field:has(input:invalid:not(:placeholder-shown)) .error {display: block;}/* Style label when input is focused */.form-field:has(input:focus) label {color: blue;transform: translateY(-1.5rem) scale(0.9);}
What makes :has() revolutionary:
:is() and :where()These pseudo-classes simplify complex selectors and reduce specificity issues.
Interview question: "What's the difference between :is() and :where()?"
/* Without :is() - repetitive */.header a:hover,.footer a:hover,.sidebar a:hover {color: blue;}/* With :is() - concise */:is(.header, .footer, .sidebar) a:hover {color: blue;}/* :where() - zero specificity */:where(.button) {background: gray;}.button.primary {background: blue; /* Easily overrides */}
Key difference:
:is() has specificity of its most specific argument:where() always has zero specificityLogical properties adapt to writing direction (LTR/RTL) automatically.
Interview question: "What are CSS logical properties and why are they important?"
/* Physical properties (direction-dependent) */.physical {margin-left: 1rem;margin-right: 2rem;}/* Logical properties (direction-independent) */.logical {margin-inline-start: 1rem; /* left in LTR, right in RTL */margin-inline-end: 2rem; /* right in LTR, left in RTL */}
Logical property mapping:
| Physical | Logical |
|---|---|
margin-left | margin-inline-start |
margin-right | margin-inline-end |
margin-top | margin-block-start |
margin-bottom | margin-block-end |
width | inline-size |
height | block-size |
Why logical properties matter:
Cascade layers provide explicit control over CSS specificity and cascade order.
Interview question: "What are cascade layers and how do they help manage CSS at scale?"
/* Define layer order (lowest to highest priority) */@layer reset, base, components, utilities;/* Add styles to layers */@layer reset {* {margin: 0;padding: 0;box-sizing: border-box;}}@layer components {.button {padding: 0.5rem 1rem;background: blue;}}
Layer priority:
/* Later layers win, regardless of specificity */@layer base {#id.class {color: red; /* High specificity, but in earlier layer */}}@layer components {.simple {color: blue; /* Wins! Even with lower specificity */}}
Why layers matter:
The aspect-ratio property maintains an element's width-to-height ratio.
/* Modern way */.video {aspect-ratio: 16 / 9;width: 100%;}/* Square */.avatar {aspect-ratio: 1;width: 100px; /* Height will be 100px */}
Practical examples:
/* Responsive image grid */.image-grid {display: grid;grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));gap: 1rem;}.image-grid img {aspect-ratio: 1;width: 100%;object-fit: cover;}
Interviewers aren't testing if you've memorized Tailwind classes. They want to understand:
Utility-first pros:
Utility-first cons:
How to articulate your understanding:
The key is showing you understand the trade-offs, not claiming one approach is universally better. For example:
It depends on the project context. Tailwind excels when you need rapid prototyping and design consistency across a component-based application. The utility-first approach reduces context switching and eliminates naming decisions. However, it does couple styles to markup, which some teams find harder to maintain. For content-heavy sites with diverse layouts, or teams new to utility-first CSS, traditional approaches might be more appropriate. I'd evaluate based on team experience, project requirements, and long-term maintainability needs.
This shows you can think critically about tools rather than following trends blindly.
Flexbox patterns:
<!-- Center content --><div class="flex min-h-screen items-center justify-center"><div>Centered content</div></div><!-- Space between --><nav class="flex items-center justify-between p-4"><div>Logo</div><div>Menu</div></nav><!-- Responsive direction --><div class="flex flex-col gap-4 md:flex-row"><div>Stacks on mobile, row on desktop</div></div>
Grid patterns:
<!-- Auto-fit grid --><div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3"><div>Card 1</div><div>Card 2</div><div>Card 3</div></div><!-- Sidebar layout --><div class="grid grid-cols-[250px_1fr] gap-4"><aside>Sidebar</aside><main>Content</main></div>
Spacing utilities:
<!-- Padding and margin --><div class="mx-auto p-4">Content</div><div class="px-4 py-2">Horizontal and vertical padding</div><!-- Space between children --><div class="space-y-4"><div>Item 1</div><div>Item 2</div></div>
@applyWhen it's helpful:
/* Extracting repeated patterns */.btn {@apply rounded px-4 py-2 font-medium transition-colors;}.btn-primary {@apply btn bg-blue-500 text-white hover:bg-blue-600;}
When it becomes an anti-pattern:
/* ❌ Defeats the purpose of utility-first */.card {@apply space-y-4 rounded-lg bg-white p-6 shadow-md;}/* You've just recreated traditional CSS! */
Better alternative - component abstraction:
// React component (better than @apply)function Button({ variant = 'primary', children }) {const baseClasses = 'px-4 py-2 rounded font-medium transition-colors';const variantClasses = {primary: 'bg-blue-500 text-white hover:bg-blue-600',secondary: 'bg-gray-200 text-gray-800 hover:bg-gray-300',};return (<button className={clsx(baseClasses, variantClasses[variant])}>{children}</button>);}
Just-In-Time (JIT) compilation:
JIT generates styles on-demand as you write them, enabling:
Arbitrary values:
<!-- Custom spacing --><div class="mt-[137px]">Custom margin</div><!-- Custom colors --><div class="bg-[#1da1f2]">Twitter blue</div><!-- Custom sizes --><div class="w-[347px]">Exact width</div><!-- With CSS variables --><div class="bg-[var(--brand-color)]">Variable color</div>
How you should think about it:
Arbitrary values are escape hatches for one-off designs. Use them when you need a specific value that doesn't fit the design system, but don't abuse them - if you're using the same arbitrary value repeatedly, it should be in your config.
md:, lg:)Very common interview question: "How does responsive design work in Tailwind?"
Breakpoint system:
<!-- Mobile-first approach --><div class="text-sm md:text-base lg:text-lg xl:text-xl">Responsive text size</div><!-- Default breakpoints:sm: 640pxmd: 768pxlg: 1024pxxl: 1280px2xl: 1536px-->
Common responsive patterns:
<!-- Responsive grid --><div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3"><div>Card</div></div><!-- Hide/show at breakpoints --><div class="hidden md:block">Only visible on tablet and up</div><div class="block md:hidden">Only visible on mobile</div><!-- Responsive spacing --><div class="p-4 md:p-6 lg:p-8">More padding on larger screens</div>
What to emphasize:
Tailwind uses a mobile-first approach. Classes without prefixes apply to all screen sizes, and prefixed classes apply from that breakpoint up. This matches modern CSS best practices and makes responsive design intuitive.
This section is where most candidates struggle - and where you can truly stand out. Interviewers use scenarios to assess problem-solving, not just knowledge recall.
Question: "You have a sticky navbar that works on desktop but doesn't stick on mobile Safari. What could be the issue?"
Common issues:
/* ❌ Problem 1: Parent has overflow hidden */.parent {overflow: hidden; /* Sticky won't work! */}/* ✅ Solution: Remove overflow or use overflow: clip */.parent {overflow: clip; /* Allows sticky to work */}/* ❌ Problem 2: Mobile Safari viewport units */.navbar {position: sticky;top: 0;height: 10vh; /* Safari's vh includes address bar */}/* ✅ Solution: Use dvh (dynamic viewport height) */.navbar {position: sticky;top: 0;height: 10dvh; /* Accounts for mobile browser UI */}
Example answer:
I'd first check if the parent container has
overflow: hidden, which breaks sticky positioning. Then I'd verify the sticky element has room to scroll. For mobile Safari specifically, I'd check if we're usingvhunits - Safari's viewport height includes the address bar, so I'd switch todvh(dynamic viewport height) or fixed pixel values.
Question: "You set z-index: 9999 on a modal, but it still appears behind other elements. Why?"
/* ❌ Modal has high z-index but is trapped */.sidebar {position: relative;z-index: 1;transform: translateX(0); /* Creates stacking context! */}.modal {position: fixed;z-index: 9999; /* Doesn't matter - stuck in sidebar's context */}/* ✅ Solution: Move modal outside stacking context *//* Render modal at root level in HTML *//* ✅ Or remove stacking context creator */.sidebar {position: relative;z-index: 1;/* Remove transform */}
Example answer:
The issue is likely a stacking context. Even with
z-index: 9999, the modal is isolated within a parent's stacking context. Common culprits aretransform,opacity < 1,filter, orwill-change. I'd inspect the DOM tree to find which parent creates the stacking context, then either move the modal to the root level or remove the stacking context creator.
Question: "You have a flex container with text that overflows instead of wrapping. How do you fix it?"
/* ❌ Problem: Flex items won't shrink below content size */.item {flex: 1;/* min-width defaults to 'auto' (content size) */}/* ✅ Solution: Override min-width */.item {flex: 1;min-width: 0; /* Allow shrinking below content size */}.item p {overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}
Example answer:
Flex items have
min-width: autoby default, which prevents them from shrinking below their content size. I'd setmin-width: 0on the flex item to allow it to shrink. Then I'd handle the text overflow with eithertext-overflow: ellipsisfor truncation orword-breakfor wrapping.
Question: "Your CSS Grid layout looks perfect on desktop but breaks on mobile with horizontal scrolling. What's wrong?"
/* ❌ Problem: Fixed column widths */.grid {display: grid;grid-template-columns: 300px 300px 300px; /* Overflows on mobile */}/* ✅ Solution: Responsive columns with minmax */.grid {display: grid;grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));gap: 1rem;}/* ✅ Or breakpoint-based columns */.grid {grid-template-columns: 1fr; /* Mobile: single column */}@media (min-width: 768px) {.grid {grid-template-columns: repeat(2, 1fr); /* Tablet: 2 columns */}}
Question: "Your animation is janky and causing performance issues. How do you optimize it?"
/* ❌ Problem: Animating layout properties */.slow-animation {transition:width 0.3s,left 0.3s;}.slow-animation:hover {width: 300px; /* Triggers layout */left: 100px; /* Triggers layout */}/* ✅ Solution: Use transform and opacity only */.fast-animation {transition:transform 0.3s,opacity 0.3s;will-change: transform;}.fast-animation:hover {transform: translateX(100px) scale(1.2); /* GPU-accelerated */opacity: 0.8; /* GPU-accelerated */}
Performance checklist:
transform and opacitywill-change sparingly (memory cost)width, height, top, leftQuestion: "You need to center a modal both horizontally and vertically, but it should scroll if content exceeds viewport height. How?"
/* ❌ Problem: Fixed positioning breaks scrolling */.modal-overlay {position: fixed;inset: 0;display: flex;align-items: center;justify-content: center;}.modal {max-height: 90vh;/* If content exceeds 90vh, it's cut off! */}/* ✅ Solution: Allow scrolling with proper overflow */.modal-overlay {position: fixed;inset: 0;display: flex;align-items: center;justify-content: center;padding: 2rem;overflow-y: auto; /* Allow scrolling */}.modal {max-width: 600px;width: 100%;margin: auto; /* Centers when scrolling */}
Question: "Implement dark mode that respects user preferences but allows manual override".
/* ✅ System preference detection */:root {--bg-color: #ffffff;--text-color: #000000;}@media (prefers-color-scheme: dark) {:root {--bg-color: #1a1a1a;--text-color: #ffffff;}}/* ✅ Manual override with data attribute */[data-theme='light'] {--bg-color: #ffffff;--text-color: #000000;}[data-theme='dark'] {--bg-color: #1a1a1a;--text-color: #ffffff;}/* Usage */body {background-color: var(--bg-color);color: var(--text-color);}
// JavaScript for manual toggleconst theme = localStorage.getItem('theme') || 'auto';if (theme === 'auto') {document.documentElement.removeAttribute('data-theme');} else {document.documentElement.setAttribute('data-theme', theme);}
When you're asked to debug CSS during a live coding interview, your DevTools skills reveal your experience level.
Essential DevTools skills:
Other techniques:
Interviewers want to understand your thought process. Silent coding makes them nervous.
The framework:
1. Over-engineering
Start simple, iterate. Don't build a complex solution when a simple one works.
2. Ignoring accessibility
<!-- ❌ Not accessible --><div onclick="handleClick()">Click me</div><!-- ✅ Accessible --><button type="button" onclick="handleClick()">Click me</button>
3. Not testing edge cases
Always test:
4. Forgetting browser compatibility
I'm using CSS Grid here, which has excellent browser support in modern browsers. If we needed to support IE11, I'd use Flexbox instead.
5. Not asking clarifying questions
Good questions to ask:
Today's interviewers want to see how you think, how you solve problems, and whether you understand the "why" behind CSS patterns - not just the "what".
The candidates who succeed aren't necessarily those who've memorized every CSS property. They're the ones who can:
Modern CSS knowledge - Container Queries, :has(), clamp(), logical properties - signals that you're staying current with the platform. But clarity in reasoning is what gets you hired.
Your next steps:
Practice real scenarios instead of memorizing Q&A. Build actual components, debug real issues, and explain your decisions out loud.
Master DevTools. Spend time exploring the Layout panel, Performance tab, and Accessibility inspector. These tools are your best friends in interviews.
Build a mental framework for approaching CSS problems:
Stay curious. CSS is evolving rapidly. Follow blogs, experiment with new features, and understand browser compatibility.
Get hands-on practice. Head over to GreatFrontEnd's CSS questions to practice build real components and practice for next interview.
Remember: companies aren't just hiring CSS experts - they're hiring problem solvers who can communicate clearly, work collaboratively, and build accessible, performant user interfaces.

Remember the first time you added TypeScript to a React project? The initial excitement of autocomplete and type safety quickly turned into frustration with cryptic error messages and confusing type definitions. You're not alone - this is the reality for most developers making the switch.
TypeScript with React has become the industry standard. React 19, Next.js 16, and virtually every modern framework now ship with first-class TypeScript support. Companies expect it, teams rely on it, and your career growth depends on mastering it.
But here's the problem: most developers learn TypeScript reactively, fixing errors as they appear rather than understanding the patterns that prevent them. This leads to codebases filled with any types, overly complex generics, and brittle component APIs that break during refactoring.
The cost is real. A single poorly-typed component can cascade into hours of debugging. Missing event handler types lead to runtime crashes. Incorrect hook typing creates subtle bugs that only appear in production.
This post reveals the 12 most common TypeScript mistakes React developers make and shows you exactly how to fix them. You'll learn the patterns senior developers use, understand why certain approaches work better than others, and gain the confidence to write type-safe React code from day one.
Ready to level up your TypeScript skills? Let's dive in. And when you're done, head over to GreatFrontEnd's TypeScript interview questions to practice and prepare for your next interview.
TypeScript isn't just about catching bugs - it's about building better software faster.
Type safety means catching errors before they reach production. Instead of discovering that user.profile.avatar is undefined at 2 AM when your app crashes, TypeScript tells you at compile time. No more defensive coding with endless null checks.
Productivity gains are immediate and measurable. IntelliSense shows you every available prop as you type. Autocomplete writes half your code for you. Refactoring a component name? TypeScript updates every import automatically. What used to take hours now takes minutes.
Collaboration improves dramatically. Your component's props are self-documenting. New team members understand your API without reading documentation. Code reviews focus on logic, not "what does this parameter do?"
Hiring trends are clear: 78% of React job postings now require TypeScript experience. It's no longer optional - it's expected.
// ❌ Without TypeScript - Runtime error waiting to happenfunction UserProfile({ user }) {return <div>{user.profile.name}</div>;}// ✅ With TypeScript - Error caught at compile timetype User = {profile?: {name: string;};};function UserProfile({ user }: { user: User }) {return <div>{user.profile?.name ?? 'Anonymous'}</div>;}
Did you know? Teams using TypeScript report 15% fewer production bugs and 20% faster onboarding for new developers.
React.FC seems convenient - it types children automatically and provides type inference. But it comes with hidden costs that experienced teams avoid.
What React.FC does:
children in props (even when you don't want it)displayName, propTypes, and other legacy propertiesWhy explicit typing is clearer:
// ❌ Using React.FC - children included even when not neededconst Button: React.FC<{ onClick: () => void }> = ({ onClick }) => {return <button onClick={onClick}>Click me</button>;};// This compiles but shouldn't - Button doesn't render children!<Button onClick={handleClick}><span>This text is ignored</span></Button>;// ✅ Explicit prop typing - clear and intentionaltype ButtonProps = {onClick: () => void;};function Button({ onClick }: ButtonProps) {return <button onClick={onClick}>Click me</button>;}// ❌ TypeScript error - children not accepted<Button onClick={handleClick}><span>Error!</span></Button>;
When teams avoid React.FC:
Using any for props defeats the entire purpose of TypeScript. Your components become black boxes, autocomplete disappears, and refactoring becomes dangerous.
Why any breaks correctness:
// ❌ Props typed as any - no safety, no autocompletefunction Card({ title, description, variant }: any) {return (<div className={variant}><h2>{title}</h2><p>{description}</p></div>);}// This compiles but crashes at runtime<Card variant={123} />;
Proper typing with optional props and variants:
// ✅ Explicit prop types with variantstype CardProps = {title: string;description?: string; // Optional propvariant?: 'primary' | 'secondary' | 'danger'; // Union type for variantsonClose?: () => void;};function Card({ title, description, variant = 'primary', onClose }: CardProps) {return (<div className={`card card--${variant}`}><h2>{title}</h2>{description && <p>{description}</p>}{onClose && <button onClick={onClose}>×</button>}</div>);}// ✅ TypeScript catches errors<Card title="Hello" variant="invalid" />; // Error: Type '"invalid"' is not assignable
Real-world design system example:
type TagProps = {label: string;size?: 'sm' | 'md' | 'lg';color?: 'blue' | 'green' | 'red' | 'gray';removable?: boolean;onRemove?: () => void;};function Tag({label,size = 'md',color = 'gray',removable = false,onRemove,}: TagProps) {return (<span className={`tag tag--${size} tag--${color}`}>{label}{removable && <button onClick={onRemove}>×</button>}</span>);}
Key takeaway: Always type your TypeScript React components explicitly. Mark optional props with ? and use union types for variants.
Event handlers are one of the most commonly mistyped patterns in React. Using Function or any seems harmless until you need to access event.target.value and TypeScript can't help you.
Common misuse:
// ❌ Too loose - no type safetyfunction SearchInput({ onChange }: { onChange: Function }) {return <input onChange={onChange} />;}// ❌ Using any - defeats the purposefunction SearchInput({ onChange }: { onChange: any }) {return <input onChange={onChange} />;}
Correct event type patterns:
// ✅ Proper event typingtype SearchInputProps = {onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;};function SearchInput({ onChange }: SearchInputProps) {return <input type="text" onChange={onChange} />;}// Usage with full type safetyfunction App() {const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {console.log(event.target.value); // ✅ TypeScript knows this is a string};return <SearchInput onChange={handleSearch} />;}
Event types mapped to elements:
| Element type | Event type | Common use case |
|---|---|---|
<input>, <textarea> | React.ChangeEvent<HTMLInputElement> | Form inputs |
<form> | React.FormEvent<HTMLFormElement> | Form submission |
<button>, <div> | React.MouseEvent<HTMLButtonElement> | Click handlers |
<input> | React.KeyboardEvent<HTMLInputElement> | Keyboard shortcuts |
<input> | React.FocusEvent<HTMLInputElement> | Focus/blur events |
Real-world form validation scenario:
type LoginFormProps = {onSubmit: (email: string, password: string) => void;};function LoginForm({ onSubmit }: LoginFormProps) {const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {event.preventDefault();const formData = new FormData(event.currentTarget);const email = formData.get('email') as string;const password = formData.get('password') as string;onSubmit(email, password);};return (<form onSubmit={handleSubmit}><input name="email" type="email" required /><input name="password" type="password" required /><button type="submit">Login</button></form>);}
forwardRef typing confusionforwardRef is notoriously tricky to type correctly. The generic syntax is confusing, and combining it with custom props often leads to type errors that are hard to debug.
Why forwardRef is tricky:
// ❌ Common mistake - ref type is wrongconst Input = forwardRef((props, ref) => {return <input ref={ref} {...props} />;});// Error: Type 'ForwardedRef<unknown>' is not assignable to type 'LegacyRef<HTMLInputElement>'
Correct generic syntax:
// ✅ Proper forwardRef typingtype InputProps = {placeholder?: string;error?: boolean;};const Input = forwardRef<HTMLInputElement, InputProps>(({ placeholder, error }, ref) => {return (<inputref={ref}placeholder={placeholder}className={error ? 'input--error' : 'input'}/>);},);Input.displayName = 'Input';
Common error messages and fixes:
| Error message | Fix |
|---|---|
Type 'ForwardedRef<unknown>' is not assignable | Add generic types: forwardRef<ElementType, PropsType> |
Property 'displayName' does not exist | Add ComponentName.displayName = 'Name' after definition |
Type instantiation is excessively deep | Simplify prop spreading or use ComponentPropsWithoutRef |
useState with complex statesTypeScript can infer simple useState types, but it fails with complex objects, null unions, and API data. Explicit typing prevents runtime errors and improves autocomplete.
When inference fails:
// ❌ TypeScript infers type as undefined, can't add user laterconst [user, setUser] = useState();// Later in code...setUser({ id: 1, name: 'John' }); // Error: Argument of type '{ id: number; name: string; }' is not assignable
Null unions and API data patterns:
// ✅ Explicit typing with null uniontype User = {id: number;name: string;email: string;avatar?: string;};const [user, setUser] = useState<User | null>(null);// ✅ TypeScript knows user can be nullif (user) {console.log(user.name); // Safe access}
Auth/profile data example:
type AuthState = {user: User | null;isAuthenticated: boolean;isLoading: boolean;};function useAuth() {const [auth, setAuth] = useState<AuthState>({user: null,isAuthenticated: false,isLoading: true,});const login = async (email: string, password: string) => {setAuth((prev) => ({ ...prev, isLoading: true }));try {const user = await api.login(email, password);setAuth({ user, isAuthenticated: true, isLoading: false });} catch (error) {setAuth({ user: null, isAuthenticated: false, isLoading: false });}};return { auth, login };}
useRef typingRefs need careful typing because they start as null and get assigned later. Mistyping refs leads to runtime errors when accessing .current.
Why refs need null initial value:
// ❌ Wrong - TypeScript thinks ref is always HTMLInputElementconst inputRef = useRef<HTMLInputElement>();// Later...inputRef.current.focus(); // Error: Object is possibly 'undefined'
Matching element types:
// ✅ Correct - ref can be null initiallyconst inputRef = useRef<HTMLInputElement>(null);// ✅ Safe access with optional chainingconst focusInput = () => {inputRef.current?.focus();};return <input ref={inputRef} />;
Mutable value refs vs DOM refs:
// ✅ DOM ref - starts as nullconst buttonRef = useRef<HTMLButtonElement>(null);// ✅ Mutable value ref - doesn't need nullconst renderCount = useRef<number>(0);useEffect(() => {renderCount.current += 1;});// ✅ Storing previous valueconst prevValue = useRef<string>();useEffect(() => {prevValue.current = value;}, [value]);
useReducer without discriminated unionsString-based action types are error-prone. Discriminated unions make reducers type-safe and eliminate entire classes of bugs.
Why string action types are risky:
// ❌ Unsafe - typos compile but break at runtimefunction reducer(state, action) {switch (action.type) {case 'LOAD_START':return { ...state, loading: true };case 'LOAD_SUCESS': // Typo! This case never matchesreturn { ...state, loading: false, data: action.payload };}}
Discriminated unions enforce strictness:
// ✅ Type-safe reducer with discriminated unionstype LoadingState = {status: 'idle' | 'loading' | 'success' | 'error';data: string | null;error: string | null;};type Action =| { type: 'LOAD_START' }| { type: 'LOAD_SUCCESS'; payload: string }| { type: 'LOAD_ERROR'; error: string };function reducer(state: LoadingState, action: Action): LoadingState {switch (action.type) {case 'LOAD_START':return { status: 'loading', data: null, error: null };case 'LOAD_SUCCESS':return { status: 'success', data: action.payload, error: null };case 'LOAD_ERROR':return { status: 'error', data: null, error: action.error };default:return state;}}
Example with loading, success, error:
function DataFetcher() {const [state, dispatch] = useReducer(reducer, {status: 'idle',data: null,error: null,});const fetchData = async () => {dispatch({ type: 'LOAD_START' });try {const data = await api.getData();dispatch({ type: 'LOAD_SUCCESS', payload: data });} catch (error) {dispatch({ type: 'LOAD_ERROR', error: error.message });}};return (<div>{state.status === 'loading' && <Spinner />}{state.status === 'success' && <div>{state.data}</div>}{state.status === 'error' && <Error message={state.error} />}</div>);}
useContext without proper type guardsContext can resolve to undefined if consumed outside a provider. Type guards prevent runtime crashes and improve developer experience.
Why context can be undefined:
// ❌ Context might be undefinedconst UserContext = createContext<User | undefined>(undefined);function useUser() {const user = useContext(UserContext);return user; // Could be undefined!}// Later...function Profile() {const user = useUser();return <div>{user.name}</div>; // Runtime error if no provider!}
Safe custom hook pattern:
// ✅ Type guard ensures context is always definedconst UserContext = createContext<User | undefined>(undefined);function useUser() {const user = useContext(UserContext);if (!user) {throw new Error('useUser must be used within UserProvider');}return user;}// Now user is always definedfunction Profile() {const user = useUser(); // TypeScript knows user is User, not User | undefinedreturn <div>{user.name}</div>; // Safe!}
Complete example:
type Theme = {primary: string;secondary: string;background: string;};const ThemeContext = createContext<Theme | undefined>(undefined);export function ThemeProvider({ children }: { children: React.ReactNode }) {const theme: Theme = {primary: '#007bff',secondary: '#6c757d',background: '#ffffff',};return (<ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>);}export function useTheme() {const theme = useContext(ThemeContext);if (!theme) {throw new Error('useTheme must be used within ThemeProvider');}return theme;}
useMemo and useCallback type inference issuesTypeScript usually infers types for useMemo and useCallback, but complex scenarios require explicit typing for correctness and performance.
When explicit typing is necessary:
// ❌ Type inference fails with complex return typesconst processedData = useMemo(() => {return items.map((item) => ({...item,computed: expensiveCalculation(item),}));}, [items]);// TypeScript might infer too broad a type
Generic parameters:
// ✅ Explicit typing for claritytype ProcessedItem = {id: number;name: string;computed: number;};const processedData = useMemo<ProcessedItem[]>(() => {return items.map((item) => ({id: item.id,name: item.name,computed: expensiveCalculation(item),}));}, [items]);
Dependency array type checking:
// ✅ useCallback with explicit typesconst handleSubmit = useCallback((event: React.FormEvent<HTMLFormElement>) => {event.preventDefault();onSubmit(formData);},[formData, onSubmit], // TypeScript checks these dependencies);
Utility types like Pick, Omit, and Partial reduce duplication and make prop types more maintainable.
Common utility types:
type User = {id: number;name: string;email: string;password: string;createdAt: Date;};// ✅ Pick - select specific propertiestype UserPreview = Pick<User, 'id' | 'name'>;// ✅ Omit - exclude propertiestype PublicUser = Omit<User, 'password'>;// ✅ Partial - make all properties optionaltype UserUpdate = Partial<User>;// ✅ Required - make all properties requiredtype CompleteUser = Required<User>;// ✅ Readonly - make all properties readonlytype ImmutableUser = Readonly<User>;// ✅ Record - create object type with specific keystype UserRoles = Record<'admin' | 'user' | 'guest', boolean>;
Design system usage:
// ✅ Base button propstype BaseButtonProps = {variant: 'primary' | 'secondary' | 'danger';size: 'sm' | 'md' | 'lg';disabled?: boolean;loading?: boolean;};// ✅ Icon button omits size, adds icontype IconButtonProps = Omit<BaseButtonProps, 'size'> & {icon: React.ReactNode;};// ✅ Link button picks variant, adds hreftype LinkButtonProps = Pick<BaseButtonProps, 'variant'> & {href: string;external?: boolean;};
The children prop has multiple possible types. Using the wrong one causes type errors and limits component flexibility.
When to use each type:
// ✅ ReactNode - accepts anything renderabletype ContainerProps = {children: React.ReactNode; // string, number, JSX, array, null, etc.};function Container({ children }: ContainerProps) {return <div className="container">{children}</div>;}// ✅ ReactElement - only accepts JSX elementstype WrapperProps = {children: React.ReactElement; // Must be a single JSX element};function Wrapper({ children }: WrapperProps) {return <div className="wrapper">{children}</div>;}// ✅ JSX.Element - similar to ReactElementtype LayoutProps = {children: JSX.Element;};// ✅ string - only accepts stringstype LabelProps = {children: string;};function Label({ children }: LabelProps) {return <label>{children.toUpperCase()}</label>;}
Render prop patterns:
// ✅ Render prop with function typetype DataListProps<T> = {data: T[];renderItem: (item: T, index: number) => React.ReactNode;};function DataList<T>({ data, renderItem }: DataListProps<T>) {return (<ul>{data.map((item, index) => (<li key={index}>{renderItem(item, index)}</li>))}</ul>);}// Usage<DataList data={users} renderItem={(user) => <UserCard user={user} />} />;
Extending native HTML attributes improves autocomplete and type safety when spreading props.
Extending HTML attributes:
// ❌ Props don't extend native attributestype ButtonProps = {variant: 'primary' | 'secondary';};function Button({ variant, ...props }: ButtonProps) {return <button {...props} className={`btn btn--${variant}`} />;}// No autocomplete for onClick, disabled, etc.// ✅ Extend native button attributestype ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {variant: 'primary' | 'secondary';};function Button({ variant, ...props }: ButtonProps) {return <button {...props} className={`btn btn--${variant}`} />;}// Full autocomplete for all button attributes!
ComponentPropsWithoutRef and ComponentPropsWithRef:
// ✅ ComponentPropsWithoutRef - for components without reftype InputProps = React.ComponentPropsWithoutRef<'input'> & {label: string;error?: string;};function Input({ label, error, ...props }: InputProps) {return (<div><label>{label}</label><input {...props} />{error && <span>{error}</span>}</div>);}// ✅ ComponentPropsWithRef - for components with reftype ButtonProps = React.ComponentPropsWithRef<'button'> & {variant: 'primary' | 'secondary';};const Button = forwardRef<HTMLButtonElement, ButtonProps>(({ variant, ...props }, ref) => {return <button ref={ref} {...props} className={`btn btn--${variant}`} />;},);
Generic components are powerful but easy to mistype. Proper constraints and polymorphic patterns make them type-safe.
Common pitfalls:
// ❌ No constraints - T could be anythingfunction List<T>({ items }: { items: T[] }) {return (<ul>{items.map((item) => (<li>{item}</li>))}</ul>);}// Error: 'item' is of type 'unknown'
Proper constraint usage:
// ✅ Constrain T to have an idtype HasId = {id: string | number;};function List<T extends HasId>({ items }: { items: T[] }) {return (<ul>{items.map((item) => (<li key={item.id}>{JSON.stringify(item)}</li>))}</ul>);}
Polymorphic component pattern (the "as" prop):
// ✅ Polymorphic componenttype BoxProps<T extends React.ElementType = 'div'> = {as?: T;children: React.ReactNode;}function Box<T extends React.ElementType = 'div'>({as,children,...props}: BoxProps<T> & Omit<React.ComponentPropsWithoutRef<T>, keyof BoxProps<T>>) {const Component = as || 'div';return <Component {...props}>{children}</Component>;}// Usage<Box>Default div</Box><Box as="section">Section element</Box><Box as="a" href="/home">Link element with href autocomplete!</Box>
Flexible Table component:
type Column<T> = {key: keyof T;header: string;render?: (value: T[keyof T], item: T) => React.ReactNode;};type TableProps<T extends Record<string, any>> = {data: T[];columns: Column<T>[];};function Table<T extends Record<string, any>>({data,columns,}: TableProps<T>) {return (<table><thead><tr>{columns.map((col) => (<th key={String(col.key)}>{col.header}</th>))}</tr></thead><tbody>{data.map((item, idx) => (<tr key={idx}>{columns.map((col) => (<td key={String(col.key)}>{col.render? col.render(item[col.key], item): String(item[col.key])}</td>))}</tr>))}</tbody></table>);}
Union types are common in React (loading states, conditional rendering), but TypeScript needs help narrowing them.
Not properly narrowing union types:
// ❌ TypeScript can't narrow the typetype State =| { status: 'loading' }| { status: 'success'; data: string }| { status: 'error'; error: string };function Display({ state }: { state: State }) {if (state.status === 'success') {return <div>{state.data}</div>; // Error: Property 'data' does not exist on type 'State'}}
Creating custom type guard functions:
// ✅ Type guard functionfunction isSuccessState(state: State,): state is { status: 'success'; data: string } {return state.status === 'success';}function Display({ state }: { state: State }) {if (isSuccessState(state)) {return <div>{state.data}</div>; // ✅ TypeScript knows state has data}}
Using discriminated unions effectively:
// ✅ Discriminated union with type narrowingtype ApiState<T> =| { status: 'idle' }| { status: 'loading' }| { status: 'success'; data: T }| { status: 'error'; error: string };function DataDisplay<T>({ state }: { state: ApiState<T> }) {switch (state.status) {case 'idle':return <div>Click to load</div>;case 'loading':return <Spinner />;case 'success':return <div>{JSON.stringify(state.data)}</div>; // ✅ data is availablecase 'error':return <Error message={state.error} />; // ✅ error is available}}
The "in" operator and typeof checks:
// ✅ Using "in" operatortype Dog = {bark: () => void;};type Cat = {meow: () => void;};type Pet = Dog | Cat;function makeSound(pet: Pet) {if ('bark' in pet) {pet.bark(); // TypeScript knows it's a Dog} else {pet.meow(); // TypeScript knows it's a Cat}}// ✅ Using typeoffunction processValue(value: string | number) {if (typeof value === 'string') {return value.toUpperCase(); // TypeScript knows it's a string} else {return value.toFixed(2); // TypeScript knows it's a number}}
Assuming API shape without types is dangerous. Create response types and consider runtime validation.
Risk of assuming API shape:
// ❌ No typing - runtime errors waiting to happenasync function fetchUser(id: number) {const response = await fetch(`/api/users/${id}`);const user = await response.json();return user; // Type is 'any'}
Generic response type:
// ✅ Type API responsestype ApiResponse<T> = {success: boolean;data?: T;error?: string;};type User = {id: number;name: string;email: string;};async function fetchUser(id: number): Promise<ApiResponse<User>> {try {const response = await fetch(`/api/users/${id}`);const data = await response.json();return { success: true, data };} catch (error) {return { success: false, error: error.message };}}
Runtime validation with Zod:
// ✅ Runtime validation with Zodimport { z } from 'zod';const UserSchema = z.object({id: z.number(),name: z.string(),email: z.string().email(),});type User = z.infer<typeof UserSchema>;async function fetchUser(id: number): Promise<User> {const response = await fetch(`/api/users/${id}`);const data = await response.json();return UserSchema.parse(data); // Throws if data doesn't match schema}
Explicit Promise<T> return types improve clarity and help catch errors early.
Why explicit Promise<T> helps:
// ❌ Implicit return type - unclear what's returnedasync function loadData() {const response = await fetch('/api/data');return response.json();}// ✅ Explicit return type - clear contractasync function loadData(): Promise<{ items: string[] }> {const response = await fetch('/api/data');return response.json();}
Impact on debugging:
// ✅ TypeScript catches mismatches immediatelyasync function getUser(id: number): Promise<User> {const response = await fetch(`/api/users/${id}`);const data = await response.json();return data; // Error if data doesn't match User type}
Not all libraries have good TypeScript support. Learn to augment types when needed.
Understanding @types/* packages:
# Install type definitions for libraries without built-in typesnpm install --save-dev @types/lodashnpm install --save-dev @types/react-router-dom
Module augmentation:
// ✅ Augment existing module typesimport 'react';declare module 'react' {interface CSSProperties {'--custom-property'?: string;}}// Now you can use custom CSS properties<div style={{ '--custom-property': 'value' }} />;
Creating your own type declarations:
// ✅ Declare module for untyped librarydeclare module 'some-untyped-library' {export function doSomething(value: string): number;export interface Config {apiKey: string;timeout?: number;}}
The declare module pattern:
// types/custom.d.tsdeclare module '*.svg' {const content: React.FunctionComponent<React.SVGAttributes<SVGElement>>;export default content;}declare module '*.png' {const value: string;export default value;}
React.FCany for propsComponentPropsWithoutRefuseState for complex statesuseRef with null for DOM refsuseReduceruseContext hooksuseMemo and useCallback when inference failsPick, Omit, Partial) to reduce duplicationReactNode, ReactElement, string)@types/* packages for untyped librariesA proper tsconfig.json is essential for catching errors and enabling the best TypeScript features.
Minimal tsconfig.json:
{"compilerOptions": {"target": "ES2020","lib": ["ES2020", "DOM", "DOM.Iterable"],"jsx": "react-jsx","module": "ESNext","moduleResolution": "bundler","strict": true,"noUncheckedIndexedAccess": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"resolveJsonModule": true,"isolatedModules": true,"noEmit": true},"include": ["src"],"exclude": ["node_modules"]}
Why strict mode matters:
Enabling "strict": true activates all strict type-checking options:
strictNullChecks - prevents null/undefined errorsstrictFunctionTypes - ensures function parameter safetystrictBindCallApply - types bind/call/apply correctlynoImplicitAny - requires explicit typesnoImplicitThis - prevents this confusionKey flags explained:
jsx: "react-jsx" - Uses the new JSX transform (React 17+), no need to import Reactjsx: "react" - Classic JSX transform, requires import ReactnoUncheckedIndexedAccess - Makes array access return T | undefined, preventing index errorsmoduleResolution: "bundler" - Modern resolution for Vite/webpack (use "node" for older setups)Top 5 confusing error messages:
What it means: You're trying to use a value where TypeScript expects a different type.
Quick fix:
// Error: Type 'string' is not assignable to type 'number'const age: number = '25';// Fix: Convert the typeconst age: number = parseInt('25');
What it means: You're accessing a property that might not exist.
Quick fix:
// Errorconst name = user.profile.name;// Fix: Use optional chainingconst name = user.profile?.name;// Or: Type guardif (user.profile) {const name = user.profile.name;}
What it means: TypeScript doesn't know about that property.
Quick fix:
// Error: Property 'customProp' does not exist<div customProp="value" />;// Fix: Extend the typedeclare module 'react' {interface HTMLAttributes<T> {customProp?: string;}}
What it means: Your types are too complex or recursive.
Quick fix:
// Simplify complex prop spreading// Instead of spreading everything, be explicitinterface ButtonProps extends Pick<React.ButtonHTMLAttributes<HTMLButtonElement>,'onClick' | 'disabled' | 'type'> {variant: string;}
What it means: React isn't imported (only needed with old JSX transform).
Quick fix:
// If using "jsx": "react-jsx", you don't need this// If using "jsx": "react", add:import React from 'react';
When to use // @ts-expect-error vs // @ts-ignore:
// ✅ Use @ts-expect-error - fails if error is fixed// @ts-expect-error: Third-party library has wrong typesconst result = poorlyTypedLibrary.method();// ❌ Avoid @ts-ignore - silently ignores errors forever// @ts-ignoreconst result = poorlyTypedLibrary.method();
VS Code extensions:
Useful TypeScript tools:
TypeScript playground:
Recommended Reading:
Practice your skills: Ready to test your knowledge? Head over to GreatFrontEnd's TypeScript Interview Questions to practice and prepare for your next interview.
After mastering these mistakes, you're prepared for these React TypeScript interview questions:
Junior Level:
interface and type in TypeScript?useState hook?ReactNode and ReactElement?Mid Level:
useReducer hook? 8. What's the difference between ComponentPropsWithRef and ComponentPropsWithoutRef?Senior Level:
TypeScript mistakes in React can be frustrating, but they're also learning opportunities. Each any type you replace, each event handler you properly type, and each hook you correctly structure makes your codebase a bit more robust.
The patterns covered here - explicit prop typing, discriminated unions, type guards, and proper generic constraints - are widely used in production codebases. They're not just theoretical best practices, but practical solutions to common problems.
If you're working on an existing codebase, consider starting small. Pick one component that uses any and give it proper types. Try adding discriminated unions to a reducer. Add a type guard to a context hook. Each improvement helps.
As you apply these patterns, you'll likely notice:
Want more practice? Check out GreatFrontEnd's TypeScript interview questions for more TypeScript interview questions on library APIs, utility types, algorithms, and building strong, typed components to prepare for your next interview.

Getting ready for an Angular interview? Whether you're a fresher or an experienced developer, this comprehensive guide will help you prepare for Angular technical interviews at top tech companies.
We've compiled essential Angular interview questions, from basic fundamentals to advanced concepts, complete with detailed answers and real-world examples.
This guide is structured to help both freshers and experienced developers prepare for Angular interviews effectively:
For freshers (0-2 years experience):
For experienced developers (2+ years):
For developers starting their Angular journey, here are the key areas to focus on:
Dive deep into 20 essential basic Angular questions →
For senior developers and architects, the focus shifts to advanced concepts:
Master 25 advanced Angular concepts →
Real-world scenarios you might encounter:
Scenario: "Our Angular application is slow with a large list of items. How would you optimize it?"
Solution:
Scenario: "Design a scalable state management solution for a large Angular application".
Solution:
Scenario: "Implement communication between deeply nested components without prop drilling".
Solution:
Explore more scenario-based Angular questions →
Not Understanding Change Detection
Misusing Observables
Poor Performance Practices
To further enhance your Angular interview preparation:
| Concept | Basic level | Advanced level |
|---|---|---|
| Components | Creation, lifecycle | Performance, architecture |
| Services | Basic DI, HTTP | Custom providers, hierarchical injection |
| State Management | Services, Inputs | Signals, RxJS patterns |
| Performance | Basic optimization | Change detection strategies, bundle optimization |
| Testing | Component tests | E2E, integration testing |
Level up your Angular interview prep with our carefully curated collection of Angular interview questions at GreatFrontEnd. Practice real UI questions from top tech companies and compare your approach with official solutions from experts.

If you're an experienced frontend developer preparing for your next Angular interview, this post is for you. With the evolving features in Angular's ecosystem - from standalone components to Signals, hydration, and zone-less change detection - interviewers now expect deep architectural understanding.
This post is part of our comprehensive Angular Interview Questions and Answers Guide. Here, we'll cover the most asked Angular Interview Questions for Experienced Professionals, including advanced, scenario-based, and performance-related topics.
If you classify yourself as:
then this list of Angular interview questions for experienced professionals will be your ultimate preparation resource.
Below is a curated list of 25 questions that target key areas - architecture, DI internals, change detection, RxJS, and performance optimization.
Angular follows Model-View-ViewModel (MVVM) pattern where:
// ViewModel (Component)export class UserComponent {users$ = this.userService.getUsers(); // Model interactionconstructor(private userService: UserService) {}deleteUser(id: string) {this.userService.deleteUser(id).subscribe();}}
The component acts as the ViewModel, managing state and handling user interactions while the template renders the view.
An NgModule in Angular is a container that groups related code-components, directives, pipes, and services-into a cohesive block of functionality. It helps organize the application into logical modules for better maintainability and reusability.
Each Angular app has at least one root module (AppModule), which bootstraps the app. Other feature modules can be created to encapsulate specific features or functionalities.
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component';@NgModule({declarations: [AppComponent], // Components, directives, pipesimports: [BrowserModule], // Other modulesproviders: [], // Servicesbootstrap: [AppComponent], // Root component})export class AppModule {}
Note: From Angular 14 onward, standalone components can be used without NgModules, but NgModules remain useful for grouping imports and providing services in larger apps.
Angular bootstrapping process:
platformBrowserDynamic().bootstrapModule(AppModule)// main.tsplatformBrowserDynamic().bootstrapModule(AppModule).catch((err) => console.error(err));
inject() API improve dependency injection compared to constructor-based DI?The inject() API, introduced in Angular 14, allows dependencies to be injected outside of class constructors, such as inside functions, factory providers, or standalone components. It provides more flexibility and cleaner code compared to constructor-based DI.
Benefits:
// Traditional constructor injectionexport class UserComponent {constructor(private userService: UserService) {}}// Using inject() APIexport class UserComponent {private userService = inject(UserService);// Can be used in functionsloadUsers = () => {const http = inject(HttpClient);return http.get('/api/users');};}
The OnPush change detection strategy improves performance by limiting when Angular checks for changes. Instead of running on every event, it only triggers when:
ChangeDetectorRef.markForCheck())This makes components more predictable and faster, especially in large apps.
How to use: Apply it in the component decorator:
@Component({changeDetection: ChangeDetectionStrategy.OnPush,template: `<div>{{ user.name }}</div>`,})export class UserComponent {@Input() user: User;constructor(private cdr: ChangeDetectorRef) {}updateUser() {// Use immutable updatesthis.user = { ...this.user, name: 'Updated' };this.cdr.detectChanges(); // Manual trigger if needed}}
Tip: Always pass new object references ({...obj} or arrays via spread) to trigger updates in OnPush components.
Lazy loading in Angular means loading feature modules or components only when needed, rather than at app startup. It improves performance by reducing the initial bundle size and speeding up load times - especially useful for large apps with multiple routes.
How to implement (module-based):
users.module.ts)loadChildren:const routes: Routes = [{path: 'users',loadChildren: () =>import('./users/users.module').then((m) => m.UsersModule),},];
Standalone component example (Angular 15+):
const routes: Routes = [{path: 'profile',loadComponent: () =>import('./profile/profile.component').then((c) => c.ProfileComponent),},];
Use it when: Your app has multiple large sections that aren't always visited (e.g., admin dashboard, reports, settings).
providers and viewProviders?Both providers and viewProviders define services that a component and its children can use - but they differ in scope.
providers - Makes the service available to the component and all its content children (including projected components via <ng-content>)viewProviders - Limits the service to the component's view only (excludes projected content)@Component({selector: 'app-parent',template: `<ng-content></ng-content>`,providers: [LoggerService], // Available to projected childrenviewProviders: [AuthService], // Only for this component's view})export class ParentComponent {}
Ahead-of-Time (AOT) Compilation is the process of compiling Angular templates and TypeScript code at build time, before the application runs in the browser.
Angular CLI uses AOT by default in production builds:
ng build --configuration production
Directives in Angular are classes that add behavior or modify the DOM. There are two main types:
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';@Directive({selector: '[appHighlight]'})export class HighlightDirective {constructor(private el: ElementRef, private renderer: Renderer2) {}@HostListener('mouseenter') onMouseEnter() {this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');}@HostListener('mouseleave') onMouseLeave() {this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');}}**Usage:**```html<p appHighlight>Hover over me!</p>
Structural directives use * syntax and manipulate the DOM.
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';@Directive({selector: '[appUnless]',})export class UnlessDirective {constructor(private templateRef: TemplateRef<any>,private vcRef: ViewContainerRef,) {}@Input() set appUnless(condition: boolean) {if (!condition) {this.vcRef.createEmbeddedView(this.templateRef);} else {this.vcRef.clear();}}}
Usage:
<p *appUnless="isVisible">I am visible only when isVisible is false</p>
declarations@Input and @Output to make directives flexible and configurableSignals and Observables both handle reactive data in Angular but differ in scope and use case.
import { signal } from '@angular/core';const count = signal(0);count.set(count() + 1);
Renderer2 work, and why is direct DOM access discouraged in Angular?Renderer2 is an Angular service that provides safe, platform-independent methods to manipulate the DOM (create elements, set styles, listen to events) without touching the browser APIs directly.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';@Directive({selector: '[appHighlight]',})export class HighlightDirective {constructor(private el: ElementRef,private renderer: Renderer2,) {}@HostListener('mouseenter') onMouseEnter() {this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');}@HostListener('mouseleave') onMouseLeave() {this.renderer.setStyle(this.el.nativeElement,'backgroundColor','transparent',);}}
Avoid direct DOM access (e.g., document.querySelector) because it breaks Angular's platform abstraction and may fail in SSR or web worker contexts.
Tree-shakable providers are services in Angular that are provided at the root level using providedIn: 'root' or in a standalone component/service, allowing unused services to be removed from the final bundle during build.
providersimport { Injectable } from '@angular/core';@Injectable({providedIn: 'root', // Tree-shakable provider})export class AuthService {login() {/* ... */}}
Only services actually used in the app are included in the production bundle, optimizing performance and load time.
Angular uses a hierarchical DI system: injectors are organized in a tree, and services are resolved top-down.
Hierarchy:
providedIn: 'root')providers or viewProvidersToken Resolution: Angular checks the component injector first, then moves up the tree to module and root injectors. If the service is not found, an error is thrown.
@Injectable({ providedIn: 'root' })export class ApiService {}@Component({selector: 'app-child',template: `<p>Child Component</p>`,providers: [ChildService],})export class ChildComponent {constructor(private api: ApiService,private childService: ChildService,) {}}
ApiService → root injector, ChildService → component injector.
Optional, Self, SkipSelf), and how are they used?Resolution modifiers control how Angular resolves dependencies in the injector hierarchy.
@Optional()null instead of throwing an errorconstructor(@Optional() private logger?: LoggerService) {}
@Self()constructor(@Self() private localService: LocalService) {}
@SkipSelf()constructor(@SkipSelf() private parentService: ParentService) {}
In large Angular applications, distant components (not parent-child) can share data using services with observables or signals.
import { Injectable } from '@angular/core';import { BehaviorSubject } from 'rxjs';@Injectable({ providedIn: 'root' })export class SharedService {private messageSource = new BehaviorSubject<string>('Hello');currentMessage$ = this.messageSource.asObservable();updateMessage(msg: string) {this.messageSource.next(msg);}}
Component A (sender):
this.sharedService.updateMessage('New Message');
Component B (receiver):
this.sharedService.currentMessage$.subscribe((msg) => console.log(msg));
import { signal, effect } from '@angular/core';export const sharedSignal = signal('Hello');// Component AsharedSignal.set('New Message');// Component Beffect(() => {console.log(sharedSignal());});
InjectionToken, and when would you use it?An InjectionToken is a unique token used to inject non-class values (e.g., strings, objects) into Angular's DI system.
Example:
import { InjectionToken, Inject } from '@angular/core';export const API_URL = new InjectionToken<string>('API_URL');@NgModule({providers: [{ provide: API_URL, useValue: 'https://api.example.com' }],})export class AppModule {}@Component({/* ... */})export class ApiService {constructor(@Inject(API_URL) private apiUrl: string) {}}
Use for: Configuration objects, strings, functions, or any non-class dependencies.
HttpClient or routing modules?HttpClient or RoutingUse Angular's testing modules to mock HTTP requests and routes without real calls.
import {HttpClientTestingModule,HttpTestingController,} from '@angular/common/http/testing';TestBed.configureTestingModule({imports: [HttpClientTestingModule],});
Use HttpTestingController to mock requests and provide test data.
import { RouterTestingModule } from '@angular/router/testing';TestBed.configureTestingModule({imports: [RouterTestingModule.withRoutes([{ path: 'home', component: MyComponent }]),],});
Use RouterTestingModule to simulate navigation and test route-related logic.
Pipes transform data in templates and can be pure or impure.
@Pipe({ name: 'pureExample', pure: true })export class PureExamplePipe implements PipeTransform {transform(value: string) {return value.toUpperCase();}}
@Pipe({ name: 'impureExample', pure: false })export class ImpureExamplePipe implements PipeTransform {transform(value: string) {return value.toUpperCase();}}
Directives in Angular modify the DOM or element behavior. They are of two types: structural and attribute.
* syntax*ngIf, *ngFor<p *ngIf="isVisible">Visible only when isVisible is true</p>
ngClass, ngStyle, custom directives<div [ngClass]="{ active: isActive }">Content</div>
*ngFor for large listsinput, scroll)shareReplay, take, debounceTime@Component({selector: 'app-list',template: `<div *ngFor="let item of items; trackBy: trackById">{{ item.name }}</div>`,changeDetection: ChangeDetectionStrategy.OnPush,})export class ListComponent {@Input() items: Item[] = [];trackById(index: number, item: Item) {return item.id;}}
Regular profiling and change detection strategy adjustments help maintain smooth performance in large Angular apps.
trackBy in *ngFor, and how does it improve rendering?trackBy helps Angular identify which items changed, preventing unnecessary DOM re-rendering.
@Component({template: `<div *ngFor="let user of users; trackBy: trackByUserId">{{ user.name }}</div>`,})export class UserListComponent {users = [{ id: 1, name: 'John' },{ id: 2, name: 'Jane' },];// Only re-renders changed items instead of recreating all DOM nodestrackByUserId(index: number, user: User): number {return user.id;}}
Benefits: Reduces DOM manipulation, improves performance for large lists, preserves component state during updates.
combineLatest, withLatestFrom, and forkJoin in RxJS.These operators handle multiple observables differently:
combineLatest - emits latest values from all observables whenever any emitscombineLatest([obs1, obs2]).subscribe(([a, b]) => console.log(a, b));
withLatestFrom - emits when the source observable emits, combining it with the latest from other observablesobs1.pipe(withLatestFrom(obs2)).subscribe(([a, b]) => console.log(a, b));
forkJoin - waits for all observables to complete, then emits the last values as an arrayforkJoin([obs1, obs2]).subscribe(([a, b]) => console.log(a, b));
Use: combineLatest for real-time updates, withLatestFrom to combine with source events, forkJoin for parallel one-time operations.
Signal effects are reactive side-effects that run automatically whenever a signal value changes similar to useEffect in React. They let you respond to state changes outside the template.
import { signal, effect } from '@angular/core';const count = signal(0);effect(() => {console.log(`Count changed: ${count()}`);});count.set(1); // Triggers effect, logs "Count changed: 1"
This error occurs when Angular detects a change to a value after change detection has run.
ngAfterViewInit or ngAfterContentInit directlysetTimeout or Promise: Delay updates to the next microtask cycle if necessaryngAfterViewInit() {setTimeout(() => {this.value = newValue; // Updates safely after change detection});}
The key is to update values before or after change detection, not during.
NgZone and how do you optimize applications using runOutsideAngular()?NgZone manages Angular's change detection, automatically triggering it when async tasks (e.g., timers, events) complete.
runOutsideAngular() to execute code without triggering change detection, e.g., for high-frequency events like scrolling or animations.import { Component, NgZone } from '@angular/core';@Component({ selector: 'app-scroll', template: `<div>Scroll Demo</div>` })export class ScrollComponent {constructor(private ngZone: NgZone) {this.ngZone.runOutsideAngular(() => {window.addEventListener('scroll', this.onScroll);});}onScroll() {console.log('Scrolling...');}}
This reduces unnecessary change detection cycles, improving performance in heavy or frequently updating scenarios.
These Angular scenario-based interview questions for experienced professionals test problem-solving in real-world situations.
When an Angular app becomes slow because of frequent change detection, you can debug and optimize using the following steps.
@Component({selector: 'app-list',templateUrl: './list.component.html',changeDetection: ChangeDetectionStrategy.OnPush,})export class ListComponent {}
<div *ngFor="let item of items; trackBy: trackById">{{ item.name }}</div>
this.ngZone.runOutsideAngular(() => {window.addEventListener('scroll', this.onScroll);});
Migrating from RxJS to Angular Signals requires careful planning to maintain reactivity and performance while reducing boilerplate.
BehaviorSubject, Observable, Subject) in components and servicesBehaviorSubject / Observable used for UI state with signals:import { signal } from '@angular/core';export class CounterComponent {count = signal(0);increment() {this.count.set(this.count() + 1);}}
import { computed } from '@angular/core';total = computed(() => this.items().reduce((sum, i) => sum + i.value, 0));
.subscribe() in templates and componentsimport { effect } from '@angular/core';effect(() => {console.log('Count changed:', this.count());});
mergeMap, combineLatest, keep RxJS to avoid complex refactorsYou can manage shared state using services with RxJS/Signals or NgRx depending on app complexity.
BehaviorSubject / signal to hold state and provide getters/setters.@Injectable({ providedIn: 'root' })export class DashboardService {// RxJSprivate widgetsSubject = new BehaviorSubject<Widget[]>([]);widgets$ = this.widgetsSubject.asObservable();updateWidgets(widgets: Widget[]) {this.widgetsSubject.next(widgets);}// Signals (Angular 16+)widgets = signal<Widget[]>([]);}
Usage in components:
this.dashboardService.widgets$.subscribe(widgets => { ... });// orthis.dashboardService.widgets.set(newWidgets);
// Actionexport const loadWidgets = createAction('[Dashboard] Load Widgets');// Reducerexport const dashboardReducer = createReducer(initialState,on(loadWidgets, (state) => ({ ...state, loading: true })),);// Selectorexport const selectWidgets = (state: AppState) => state.dashboard.widgets;
Components: Subscribe via store.select(selectWidgets) and dispatch actions to update state.
CanActivate to restrict routes based on authentication or roles@Injectable({ providedIn: 'root' })export class AuthGuard implements CanActivate {constructor(private auth: AuthService,private router: Router,) {}canActivate(): boolean {if (this.auth.isLoggedIn()) return true;this.router.navigate(['/login']);return false;}}
Usage in routing module:
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
@Injectable()export class AuthInterceptor implements HttpInterceptor {constructor(private auth: AuthService) {}intercept(req: HttpRequest<any>, next: HttpHandler) {const token = this.auth.getToken();const authReq = req.clone({setHeaders: { Authorization: `Bearer ${token}` },});return next.handle(authReq);}}
Register interceptor:
providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },];
If your Angular app's production build is large (e.g., 3MB), you can optimize it using these strategies:
{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) }
ng build --prod --optimization --build-optimizer
Combining lazy loading, tree-shaking, and asset optimization can significantly reduce bundle size.
To add Server-Side Rendering (SSR) to an existing Angular Single Page Application (SPA), I would use Angular Universal, which enables SSR for Angular apps. The steps are:
ng add @nguniversal/express-engine
This sets up a server-side app module (app.server.module.ts) and configures an Express server (server.ts) to render Angular on the server.
window, document, and localStorage - are only used in the browser contextisPlatformBrowser from @angular/commonnpm run build:ssrnpm run serve:ssr
This serves the pre-rendered HTML from the server, improving SEO and initial load performance.
Meta and Title services for better indexingResult: Users and search engines receive fully rendered HTML on the first request, improving SEO, performance, and crawlability of the Angular app.
To break down a monolithic Angular app into feature modules, I would follow these steps:
Identify Features: Analyze the app and group related functionality (components, services, and routes) into logical features like UserModule, DashboardModule, ProductsModule, etc.
Create Feature Modules: Use the Angular CLI or manually create modules:
ng generate module feature-name --route feature-name --module app.module
This sets up lazy-loaded feature modules if needed.
providedIn: FeatureModule if appropriate)feature-name-routing.module.ts) to handle internal routes{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) }
SharedModuleCoreModule imported only once in AppModuleWhen structuring unit tests for complex component hierarchies, I follow these practices:
TestBed to create a testing module for the component@Input() bindings, @Output() events, template rendering, and user interactionsdescribe blocksResult: This approach ensures each component's behavior is tested reliably while keeping tests fast, maintainable, and isolated from unrelated parts of the hierarchy.
These questions push beyond fundamentals - they're frequent in senior developer and tech lead interviews.
Angular creates a single root injector for eagerly-loaded code, while each lazy-loaded route gets its own child injector.
providedIn: 'root' → one instance in root; providedIn: 'any' → one per injector (root and each lazy)@Injectable({ providedIn: 'any' })export class FeatureService {}// Eager context and each lazy module will get different instancesconstructor(private s: FeatureService) {}
This scoping helps isolate features and avoid cross-feature state leaks while keeping true singletons in root.
Hydration attaches Angular runtime to server-rendered HTML without re-rendering it. The DOM remains; Angular wires up event listeners and state.
// main.ts (standalone app)bootstrapApplication(AppComponent, {providers: [provideClientHydration()],});// Template: defer non-critical islands to reduce hydration cost@defer (on viewport) {<heavy-widget />} @placeholder { Loading... }
Standalone components remove NgModule indirection-dependencies are imported where used, and providers are scoped closer to usage.
providers reduce accidental singletons@Component({standalone: true,selector: 'user-card',imports: [CommonModule],template: `{{ user.name }}`,providers: [UserLocalLogger],})export class UserCard {@Input() user!: User;}bootstrapApplication(AppComponent, {providers: [provideRouter(routes)],});
// Zoneless bootstrap (no global auto change detection)bootstrapApplication(AppComponent, { ngZone: 'noop' });@Component({ changeDetection: ChangeDetectionStrategy.OnPush })export class Cmp {// Prefer Signals or async pipe; call cdr.markForCheck() when bridging imperative codeconstructor(private cdr: ChangeDetectorRef) {}}
Use zoneless with Signals and async pipe for most UI; use runOutsideAngular() for high-frequency events.
Implement PreloadingStrategy to decide per-route preloading (e.g., based on flags or network conditions).
@Injectable({ providedIn: 'root' })export class SelectivePreloading implements PreloadingStrategy {preload(route: Route, load: () => Observable<any>) {return route.data?.['preload'] ? load() : of(null);}}const routes: Routes = [{path: 'admin',loadChildren: () => import('./admin/admin.routes'),data: { preload: true },},{ path: 'reports', loadChildren: () => import('./reports/reports.routes') },];provideRouter(routes, withPreloading(SelectivePreloading));
You can enrich logic with navigator.connection, user roles, or time-based delays.
source-map-analyzer to cut bundle sizes?// angular.json (excerpt){"configurations": {"production": {"budgets": [{ "type": "initial", "maximumWarning": "500kb", "maximumError": "2mb" },{ "type": "anyComponentStyle", "maximumWarning": "150kb" }]}}}
Workflow:
ng build --configuration production --stats-jsonnpx source-map-explorer dist/**/*.js (or webpack bundle analyzer)providedIn: 'root'/tree-shakable APIssubscribe() without unsubscribe → prefer async pipe or takeUntilDestroyed()switchMap, concatMap)shareReplay({ refCount: true, bufferSize: 1 }))catchError with fallbacksimport { takeUntilDestroyed } from '@angular/core/rxjs-interop';this.form.valueChanges.pipe(debounceTime(300),switchMap((v) => this.api.search(v)),takeUntilDestroyed(this.destroyRef),).subscribe((result) => this.results.set(result));
Prefer async pipe in templates; for shared streams, cache with shareReplay(1).
Core stages: install → lint → test → build (SPA/SSR) → artifact → deploy.
# .github/workflows/ci.yml (simplified)name: Angular CIon: [push, pull_request]jobs:build:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4- uses: actions/setup-node@v4with: { node-version: 20, cache: npm }- run: npm ci- run: npm run lint- run: npm test -- --watch=false --browsers=ChromeHeadless- run: npm run build:ssr # e.g., ng build && ng run app:server- uses: actions/upload-artifact@v4with: { name: dist, path: dist/ }# Deploy job can download artifact and push to hosting (Firebase, Vercel, Azure, etc.)
Include budgets in CI to block regressions; for SSR, validate hydration with e2e smoke tests before deploy.
trackBy in *ngFor to minimize DOM re-rendersasync pipe or takeUntilDestroyed()Renderer2 for cross-platform DOM-safe operationsFollowing these keeps senior developers' Angular apps maintainable and performant in large-scale setups
Here are a few resources to expand your prep:
Angular has matured rapidly with standalone APIs, fine-grained reactivity using Signals, and better SSR tooling. Interviewers now test practical knowledge - not syntax, but design reasoning and architectural excellence.
If your goal is to ace Angular Experienced Interview Questions, practice code samples, profile performance, and be ready to justify your design choices like a senior engineer.
Level up your Angular interview prep with our carefully curated collection of Angular interview questions at GreatFrontEnd. Practice real UI questions from top tech companies and compare your approach with official solutions from experts.

Got an Angular interview coming up? Whether you're new to Angular or brushing up before your Angular interview, this post is for you.
This post is part of our comprehensive Angular Interview Questions and Answers Guide, covering fundamental Angular concepts about - components, services, data binding, routing - and a few modern essentials like Signals and standalone components.
If you're looking for Angular basic interview questions or preparing for Angular interview questions for freshers, you're in the right place.
Let's jump in.
Angular is a modern, open-source framework developed by Google using TypeScript that allows developers to build dynamic, modern single-page web applications.
It provides:
Angular components are the core building blocks of any Angular application. Each component manages a specific section of the user interface called a view.
A component is made up of three key parts:
@Component, links the class with its template, selector, and stylesComponents are self-contained, reusable, and testable, forming a tree of nested components that make up the entire application.
Code example:
import { Component } from '@angular/core';@Component({selector: 'app-welcome',template: `<h2>Welcome, {{ name }}!</h2>`,styles: [`h2 {color: #1976d2;}`,],})export class WelcomeComponent {name = 'Angular Developer';}
Common follow-up: What's the difference between a component's template and templateUrl?
NgModule is a class decorated with @NgModule that defines an Angular module - a container grouping related components, directives, pipes, and services into a cohesive unit.
It helps:
Key properties in @NgModule include:
declarations - components, directives, and pipes in this moduleimports - other modules to use their featuresproviders - services available for dependency injectionexports - elements made available to other modulesCode example:
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component';import { WelcomeComponent } from './welcome.component';@NgModule({declarations: [AppComponent, WelcomeComponent],imports: [BrowserModule],providers: [],bootstrap: [AppComponent],})export class AppModule {}
Since Angular 14, standalone components can work without NgModules, but modules remain useful for organizing imports and providing services.
Data binding in Angular connects the component's data with the template (view), keeping them in sync. It lets you display values, respond to user input, and update the UI automatically.
There are two main types:
Data flows in one direction - either from component → view or view → component.
{{ value }} - shows data[property]="value" - binds DOM properties(event)="handler()" - listens to user actions<h3>{{ title }}</h3><!-- Interpolation --><img [src]="imageUrl" /><!-- Property binding --><button (click)="onClick()">Click</button><!-- Event binding -->
Data flows both ways - updates in the view reflect in the component and vice versa.
Uses the [(ngModel)] directive (requires FormsModule).
<input [(ngModel)]="username" /><p>Hello, {{ username }}!</p>
export class AppComponent {title = 'Data Binding Example';imageUrl = 'logo.png';username = '';onClick() {alert(`Hello ${this.username || 'Angular Dev'}!`);}}
Directives in Angular are classes that add behavior to elements. They let you manipulate the DOM, change appearance, or modify structure.
Types of directives:
Code example:
<!-- Component Directive --><app-greeting [name]="userName"></app-greeting><!-- Structural Directive --><div *ngIf="isVisible">Visible content</div><!-- Attribute Directive --><div [ngClass]="{'highlight': isHighlighted}">Styled content</div>
// Parent Componentimport { Component } from '@angular/core';@Component({selector: 'app-example',templateUrl: './example.component.html',})export class ExampleComponent {userName = 'Nitesh';isVisible = true;isHighlighted = false;}// Child Component (Component Directive)@Component({selector: 'app-greeting',template: `<p>Hello, {{ name }}!</p>`,})export class GreetingComponent {name = '';}
A Service is a class decorated with @Injectable() that contains business logic and data operations shared across multiple components.
Key features:
Common uses:
Code example:
import { Injectable } from '@angular/core';import { HttpClient } from '@angular/common/http';@Injectable({providedIn: 'root',})export class DataService {constructor(private http: HttpClient) {}getData() {return this.http.get('/api/data');}}
Usage in component:
export class MyComponent {constructor(private dataService: DataService) {}loadData() {this.dataService.getData().subscribe((data) => {// Handle data});}}
Common follow-up: What's the difference between providedIn: 'root' and adding a service to the providers array in a module?
Dependency Injection (DI) is a design pattern where Angular automatically provides dependencies (like services) to components instead of components creating them manually.
Key benefits:
How it works:
@Injectable() and providedInCode example:
// Service@Injectable({providedIn: 'root', // Makes the service a singleton available throughout the app})export class AuthService {isLoggedIn(): boolean {return true;}}// Componentexport class HeaderComponent {constructor(private authService: AuthService) {// authService is now an instance provided by Angular's DI}checkAuth() {return this.authService.isLoggedIn();}}
Angular creates the AuthService instance automatically and injects it into any component that needs it.
Common follow-up: What are the benefits of using Dependency Injection?
TypeScript is a superset of JavaScript that adds static typing and modern features. Angular is built with TypeScript by default.
Benefits for Angular:
Example:
interface User {id: number;name: string;email: string;}export class UserComponent {user: User = {id: 1,name: 'John Doe',email: 'john@example.com',};}
Angular Router enables navigation between different views/components in a single-page application.
Key concepts:
Basic setup:
// app-routing.module.tsconst routes: Routes = [{ path: 'home', component: HomeComponent },{ path: 'about', component: AboutComponent },{ path: '', redirectTo: '/home', pathMatch: 'full' },];
<!-- app.component.html --><nav><a routerLink="/home">Home</a><a routerLink="/about">About</a></nav><router-outlet></router-outlet>
Pipes transform data in templates without changing the original data. They're used for formatting display values.
Built-in pipes:
Usage:
<p>{{ today | date:'short' }}</p><p>{{ price | currency:'USD' }}</p><p>{{ name | uppercase }}</p><p>{{ user | json }}</p>
Custom pipe example:
import { Pipe, PipeTransform } from '@angular/core';@Pipe({ name: 'reverse' })export class ReversePipe implements PipeTransform {transform(value: string): string {return value.split('').reverse().join('');}}
Usage: <p>{{ 'Angular' | reverse }}</p> outputs "ralugnA"
Lifecycle hooks are methods that Angular calls at specific moments in a component's lifecycle.
Common hooks:
Example:
export class MyComponent implements OnInit, OnDestroy {ngOnInit() {console.log('Component initialized');}ngOnDestroy() {console.log('Component destroyed');// Cleanup subscriptions}}
Common follow-up: When should you use ngOnDestroy to clean up resources?
Event binding listens to DOM events and responds to user actions like clicks, key presses, or mouse movements.
Syntax: (event)="handler()"
Examples:
<button (click)="onClick()">Click me</button><input (keyup)="onKeyUp($event)" /><div (mouseenter)="onMouseEnter()">Hover me</div>
export class MyComponent {onClick() {console.log('Button clicked!');}onKeyUp(event: any) {console.log('Key pressed:', event.target.value);}onMouseEnter() {console.log('Mouse entered!');}}
Property binding sets DOM element properties dynamically using component data.
Syntax: [property]="expression"
Examples:
<img [src]="imageUrl" [alt]="imageAlt" /><button [disabled]="isDisabled">Submit</button><div [class.active]="isActive">Content</div><input [value]="inputValue" />
export class MyComponent {imageUrl = 'logo.png';imageAlt = 'Company Logo';isDisabled = false;isActive = true;inputValue = 'Default text';}
Interpolation displays component data in templates using double curly braces {{ }}.
Features:
Examples:
<h1>{{ title }}</h1><p>Welcome, {{ user.name }}!</p><p>Total: {{ price * quantity }}</p><p>Current time: {{ getCurrentTime() }}</p>
export class MyComponent {title = 'My App';user = { name: 'John' };price = 10;quantity = 2;getCurrentTime() {return new Date().toLocaleTimeString();}}
Signals (introduced in Angular 16) are a reactive primitive for managing state and change detection. They provide a simpler, more performant way to handle reactive data.
Key features:
Basic usage:
import { Component, signal, computed } from '@angular/core';@Component({selector: 'app-counter',template: `<p>Count: {{ count() }}</p><p>Double: {{ doubleCount() }}</p><button (click)="increment()">Increment</button>`,})export class CounterComponent {// Create a signalcount = signal(0);// Computed signal - automatically updatesdoubleCount = computed(() => this.count() * 2);increment() {// Update signal valuethis.count.update((value) => value + 1);}}
Signals improve Angular's reactivity model and are the future direction of the framework.
Standalone components (introduced in Angular 14+) are components that don't require NgModules. They simplify Angular applications by allowing components to be self-contained.
Key benefits:
Example:
import { Component } from '@angular/core';import { CommonModule } from '@angular/common';import { FormsModule } from '@angular/forms';@Component({selector: 'app-user',standalone: true,imports: [CommonModule, FormsModule],template: `<h2>{{ userName }}</h2><input [(ngModel)]="userName" />`,})export class UserComponent {userName = 'John';}
Angular 17+ introduced a new built-in control flow syntax with @if, @for, and @switch to replace structural directives like *ngIf and *ngFor.
Key features:
Examples:
<!-- Conditional rendering with @if -->@if (isLoggedIn) {<p>Welcome back!</p>} @else {<p>Please log in</p>}<!-- Loop with @for -->@for (user of users; track user.id) {<div>{{ user.name }}</div>} @empty {<p>No users found</p>}<!-- Switch statement -->@switch (status) { @case ('pending') { <span>Pending...</span> } @case('complete') { <span>Done!</span> } @default { <span>Unknown</span> } }
export class MyComponent {isLoggedIn = true;users = [{ id: 1, name: 'Alice' },{ id: 2, name: 'Bob' },];status = 'pending';}
Angular Forms handle user input, validation, and form submission. There are two approaches:
Template-driven forms:
FormsModuleReactive forms:
ReactiveFormsModuleTemplate-driven example:
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)"><input name="username" [(ngModel)]="user.username" required /><button type="submit" [disabled]="!userForm.valid">Submit</button></form>
export class MyComponent {user = { username: '' };onSubmit(form: any) {if (form.valid) {console.log(this.user);}}}
Reactive forms example:
import { FormBuilder, Validators } from '@angular/forms';export class MyComponent {userForm = this.fb.group({username: ['', Validators.required],email: ['', [Validators.required, Validators.email]],});constructor(private fb: FormBuilder) {}onSubmit() {if (this.userForm.valid) {console.log(this.userForm.value);}}}
@Input and @Output decorators enable communication between parent and child components.
@Input - passes data from parent to child:
// Child Componentexport class ChildComponent {@Input() userName: string = '';}
<!-- Parent Template --><app-child [userName]="parentName"></app-child>
@Output - sends events from child to parent:
// Child Componentexport class ChildComponent {@Output() notify = new EventEmitter<string>();sendMessage() {this.notify.emit('Hello from child!');}}
<!-- Parent Template --><app-child (notify)="handleMessage($event)"></app-child>
// Parent ComponenthandleMessage(message: string) {console.log(message);}
Observables are a key part of Angular's reactive programming approach, used extensively for handling asynchronous operations.
Key concepts:
Basic example:
import { Observable } from 'rxjs';export class DataComponent {constructor(private http: HttpClient) {}getData(): void {// HTTP returns an Observablethis.http.get('/api/users').subscribe({next: (data) => console.log(data),error: (error) => console.error(error),complete: () => console.log('Request completed'),});}}
Common RxJS operators: map, filter, switchMap, debounceTime
Remember: Always unsubscribe from Observables in ngOnDestroy to prevent memory leaks (except for HTTP requests which auto-complete).
Avoid these common pitfalls that can cost you in interviews:
ngOnDestroy to prevent memory leaks (except HTTP calls).// ❌ BadngOnInit() {this.dataService.getData().subscribe(data => this.data = data);}// ✅ Goodsubscription: Subscription;ngOnInit() {this.subscription = this.dataService.getData().subscribe(data => this.data = data);}ngOnDestroy() {this.subscription?.unsubscribe();}
[], (), and {{}} syntax{{ }} for interpolation[property] for property binding(event) for event binding[(ngModel)] for two-way bindingprovidedIn: 'root' creates app-wide singleton; providers[] creates instance per module/component.*ngIf and *ngFor@if, @for, and standalone components are now standard.ngOnInit for initialization, constructor only for dependency injection.Here's a rapid-fire review of key concepts:
| Concept | Key point |
|---|---|
| Components | Building blocks with template, class, and metadata |
| Modules | Container for organizing related components (less common with standalone) |
| Data Binding | One-way ({{ }}, [], ()) and two-way ([()]) |
| Services | Reusable business logic, injected via DI |
| Dependency Injection | Angular provides dependencies automatically |
| Directives | Add behavior to DOM elements |
| Pipes | Transform data in templates |
| Lifecycle Hooks | ngOnInit, ngOnDestroy, ngOnChanges, etc. |
| Router | Navigate between views in SPA |
| Forms | Template-driven (simple) vs Reactive (complex) |
| Observables | Handle async operations with RxJS |
| Signals | Modern reactive primitive (Angular 16+) |
| Standalone | Components without NgModules (Angular 14+) |
| Control Flow | @if, @for, @switch syntax (Angular 17+) |
Remember, every Angular developer started exactly where you are now. The fact that you're here preparing shows you're already ahead of the curve. Take a deep breath, trust in the work you've put in, and let your passion for learning shine through in your interview. You've got this! 🚀
Level up your Angular interview prep with our carefully curated collection of Angular interview questions at GreatFrontEnd. Practice real UI questions from top tech companies and compare your approach with official solutions from experts.

Preparing for a React interview can be daunting, but having access to the right questions can make all the difference. We've created a prioritized list of 100+ questions and solutions, covering essential topics like React fundamentals, React Hooks, React Router, internationalization in React, testing of React apps, and the latest React 19 features.
This comprehensive guide is designed to help you prepare effectively, boost your confidence, and ensure you make a strong impression during your interview.
What's new in the May 2026 update
- 10 new questions covering React 19: Actions,
useActionState,useOptimistic, theusehook, Server Components, the React Compiler, and form actions, in the "React 19 and modern React" section below.- Existing answers updated so function components and hooks are the default, and class-based patterns are flagged where they're now legacy.
- All code samples checked against React 19.
If you're looking for more in-depth React interview preparation materials, also check out these resources:
Mastering React fundamentals is crucial in front end interviews because most companies rely on React for building modern web applications, and interview questions often test your ability to reason about components, state management, and data flow. A solid grasp of these core concepts is an important step to achieving interview success.
React is a JavaScript library developed by Facebook for creating user interfaces, particularly in single-page applications. It enables the use of reusable components that manage their own state. Key advantages include a component-driven architecture, optimized updates through the virtual DOM, a declarative approach for better readability, and robust community backing.

Find in-depth explanations and track study progress here ->
JSX, short for JavaScript XML, is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It makes building React components easier. JSX gets converted into JavaScript function calls, often by Babel. For instance, <div>Hello, world!</div> is transformed into React.createElement('div', null, 'Hello, world!').

Find in-depth explanations and track study progress here ->
The virtual DOM is a simplified version of the actual DOM used by React. It allows for efficient UI updates by comparing the virtual DOM to the real DOM and making only the necessary changes through a process known as reconciliation.
Find in-depth explanations and track study progress here ->
The virtual DOM in React is an in-memory representation of the real DOM. When state or props change, React creates a new virtual DOM tree, compares it to the previous one using a diffing algorithm, and efficiently updates only the parts of the real DOM that changed.
Find in-depth explanations and track study progress here ->
A React Node refers to any unit that can be rendered in React, such as an element, string, number, or null. A React Element is an immutable object that defines what should be rendered, typically created using JSX or React.createElement. A React Component is either a function or class that returns React Elements, enabling the creation of reusable UI components.
Find in-depth explanations and track study progress here ->
React Fragments allow you to group multiple elements without adding extra nodes to the DOM. They are particularly useful when you need to return multiple elements from a component but don't want to wrap them in a container element. You can utilize shorthand syntax <>...</> or React.Fragment.
return (<><ChildComponent1 /><ChildComponent2 /></>);
Find in-depth explanations and track study progress here ->
key prop in React?In React, the key prop is used to uniquely identify elements in a list, allowing React to optimize rendering by updating and reordering items more efficiently. Without unique keys, React might re-render elements unnecessarily, causing performance problems and potential bugs.
{items.map((item) => <ListItem key={item.id} value={item.value} />);}
Find in-depth explanations and track study progress here ->
Using array indices as keys can lead to performance issues and unexpected behavior, especially when reordering or deleting items. React relies on keys to identify elements uniquely, and using indices can cause components to be re-rendered unnecessarily or display incorrect data.
Find in-depth explanations and track study progress here ->
Props (short for properties) are inputs to React components that allow you to pass data from a parent component to a child component. They are immutable and are used to configure a component. In contrast, state is internal to a component and can change over time, typically due to user interactions or other events.
Find in-depth explanations and track study progress here ->
Class components are ES6 classes that extend React.Component and rely on lifecycle methods (componentDidMount, componentDidUpdate, etc.) and this.state. Function components are plain functions that take props as input and return JSX, and use hooks (useState, useEffect, useRef, etc.) for state and side effects. Since hooks landed in React 16.8, function components are the default for new code; class components are kept for backward compatibility and are no longer the recommended pattern.
Default to function components. Class components are legacy: new APIs like Suspense data fetching, the use hook, Actions, Server Components, and the React Compiler are designed for function components only. The one remaining reason to write a class today is implementing an error boundary, which still requires static getDerivedStateFromError / componentDidCatch.
React Fiber is a complete rewrite of the React core algorithm, designed to improve performance and enable new features like async rendering, error boundaries, and incremental rendering. It breaks down the rendering process into smaller chunks, allowing React to pause, abort, or prioritize updates as needed.
Find in-depth explanations and track study progress here ->
Reconciliation is the process by which React updates the DOM to match the virtual DOM efficiently. It involves comparing the new virtual DOM tree with the previous one and determining the minimum number of changes required to update the actual DOM. This process ensures optimal performance by avoiding unnecessary re-renders.

Find in-depth explanations and track study progress here ->
The Shadow DOM is a web standard that encapsulates a part of the DOM, isolating it from the rest of the document. It's used for creating reusable, self-contained components without affecting the global styles or scripts.
The Virtual DOM is an in-memory representation of the actual DOM used to optimize rendering. It compares the current and previous states of the UI, updating only the necessary parts of the DOM, which improves performance.
In controlled components, form data is managed through the component's state, making it the definitive source of truth. Input value changes are handled by event handlers. In uncontrolled components, the form state is managed internally and accessed via refs. Controlled components provide more control and are easier to test, while uncontrolled components are simpler for basic use cases.
Example of a controlled component:
function ControlledInput() {const [value, setValue] = React.useState('');return (<inputtype="text"value={value}onChange={(e) => setValue(e.target.value)}/>);}
Example of an uncontrolled component:
function UncontrolledInput() {const inputRef = React.useRef();return <input type="text" ref={inputRef} />;}
Find in-depth explanations and track study progress here ->
Lifting state up in React involves moving the state from child components to their nearest common ancestor. This pattern is used to share state between components that don't have a direct parent-child relationship. By lifting state up, you can avoid prop drilling and simplify the management of shared data.
// Lifting state upconst Parent = () => {const [counter, setCounter] = useState(0);return (<div><Child1 counter={counter} /><Child2 setCounter={setCounter} /></div>);};const Child1 = ({ counter }) => <h1>{counter}</h1>;const Child2 = ({ setCounter }) => (<button onClick={() => setCounter((prev) => prev + 1)}>Increment</button>);
In this example, the state is managed in the Parent component, and both child components access it via props.
Pure Components in React are components that only re-render when their props or state change. They use shallow comparison to check if the props or state have changed, preventing unnecessary re-renders and improving performance.
React.PureComponent to become pureReact.memo for the same effectconst PureFunctionalExample = React.memo(function ({ value }) {return <div>{value}</div>;});
With the React Compiler, manual memoization with React.memo, useMemo, and useCallback is rarely needed; the compiler inserts equivalent memoization automatically.
createElement and cloneElement?The difference between createElement and cloneElement in React is as follows:
createElement:React.createElement('div', { className: 'container' }, 'Hello World');
cloneElement:const element = <button className="btn">Click Me</button>;const clonedElement = React.cloneElement(element, { className: 'btn-primary' });
PropTypes in React?PropTypes was React's runtime prop type-checker. You declared expected types, and React would warn in the console when a mismatch occurred in development.
import PropTypes from 'prop-types';function MyComponent({ name, age }) {return (<div>{name} is {age} years old</div>);}MyComponent.propTypes = {name: PropTypes.string.isRequired,age: PropTypes.number.isRequired,};
PropTypes is deprecated as of React 19 and no longer ships from the react package. Use TypeScript instead; it catches the same mismatches at compile time and integrates with editor tooling.
Stateless components in React are components that do not manage or hold any internal state. They simply receive data via props and render UI based on that data. These components are often functional components and are used for presentational purposes.
this.statepropsfunction StatelessComponent({ message }) {return <div>{message}</div>;}
Stateless components are simpler, easier to test, and often more reusable. With the introduction of hooks, React components are mostly written using functions and can contain state via the useState hook.
Stateful components in React are components that manage and hold their own internal state. They can modify their state in response to user interactions or other events and re-render themselves when the state changes.
this.state (in class components) or useState (in functional components)function StatefulComponent() {const [count, setCount] = React.useState(0);return (<div><p>{count}</p><button onClick={() => setCount(count + 1)}>Increment</button></div>);}
Stateful components are essential for handling dynamic and interactive UIs.
Use TypeScript. It catches prop mismatches at compile time, integrates with editor tooling (autocomplete, refactors, jump-to-definition), and is the default in most React project templates.
type MyComponentProps = {name: string;age: number;};function MyComponent({ name, age }: MyComponentProps) {return (<div>{name} is {age} years old</div>);}
The older alternative was PropTypes, a runtime checker that warned in dev mode when prop types didn't match. It is deprecated as of React 19 and no longer ships from the react package. If you're maintaining a codebase that still uses prop-types, migrate to TypeScript.
React advises against mutating state as it can lead to unexpected behaviors and bugs. State immutability helps efficiently determine when components need re-rendering; direct mutations may prevent React from detecting changes.
Find in-depth explanations and track study progress here ->
Mastering React hooks is important in front end interviews because hooks are the standard way to manage state, side effects, and component lifecycle in modern React. Demonstrating a solid understanding of hooks shows you can write clean, functional components and solve complex problems without relying on outdated class patterns.
Hooks enable the use of state and other React features in functional components, replacing the need for class components. They streamline code by reducing the reliance on lifecycle methods, enhance readability, and facilitate the reuse of stateful logic across components.
Popular hooks like useState and useEffect are used for managing state and side effects.
Find in-depth explanations and track study progress here ->
React hooks should be called at the top level of a function, not inside loops, conditions, or nested functions. They must only be used within React function components or custom hooks. These guidelines ensure proper state management and lifecycle behavior.
Find in-depth explanations and track study progress here ->
useEffect and useLayoutEffect in React?useEffect and useLayoutEffect both handle side effects in React functional components but differ in when they run:
useEffect runs asynchronously after the DOM has rendered, making it suitable for tasks like data fetching or subscriptions.useLayoutEffect runs synchronously after DOM updates but before the browser paints, ideal for tasks like measuring DOM elements or aligning the UI with the DOM. Example:import React, { useEffect, useLayoutEffect, useRef } from 'react';function Example() {const ref = useRef();useEffect(() => {console.log('useEffect: Runs after DOM paint');});useLayoutEffect(() => {console.log('useLayoutEffect: Runs before DOM paint');console.log('Element width:', ref.current.offsetWidth);});return <div ref={ref}>Hello</div>;}
Find in-depth explanations and track study progress here ->
useEffect affect?The dependency array of useEffect controls when the effect re-runs:
Find in-depth explanations and track study progress here ->
useRef hook in React and when should it be used?The useRef hook creates a mutable object that persists through renders, allowing direct access to DOM elements, storing mutable values without causing re-renders, and maintaining references to values.
For instance, useRef can be utilized to focus on an input element:
import React, { useRef, useEffect } from 'react';function TextInputWithFocusButton() {const inputEl = useRef(null);useEffect(() => {inputEl.current.focus();}, []);return <input ref={inputEl} type="text" />;}
Find in-depth explanations and track study progress here ->
setState() in React class components and when should it be used?This applies to class components, which are no longer the recommended pattern. The function-component equivalent (the updater form of useState) is shown at the end.
The callback (updater) form of setState() ensures state updates are based on the most current state and props. This matters when the new state depends on the previous state, because React may batch multiple updates and the this.state you'd read directly could be stale.
this.setState((prevState, props) => ({counter: prevState.counter + props.increment,}));
The function-component equivalent uses the updater form of useState:
const [counter, setCounter] = useState(0);setCounter((prev) => prev + props.increment);
Find in-depth explanations and track study progress here ->
useCallback hook in React and when should it be used?The useCallback hook memoizes functions to prevent their recreation on every render. This is especially beneficial when passing callbacks to optimized child components that depend on reference equality to avoid unnecessary renders. Use it when a function is passed as a prop to a memoized child component.
const memoizedCallback = useCallback(() => {doSomething(a, b);}, [a, b]);
With the React Compiler enabled, you rarely need useCallback manually; the compiler inserts equivalent memoization automatically.
Find in-depth explanations and track study progress here ->
useMemo hook in React and when should it be used?The useMemo hook memoizes costly calculations, recomputing them only when dependencies change. This enhances performance by avoiding unnecessary recalculations. It should be used for computationally intensive functions that don't need to run on every render.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
With the React Compiler enabled, you rarely need useMemo manually; the compiler memoizes derived values automatically.
Find in-depth explanations and track study progress here ->
useReducer hook in React and when should it be used?The useReducer hook manages complex state logic in functional components, serving as an alternative to useState. It's ideal when state has multiple fields (and there are constraints around how they should be mutated), or when the next state relies on the previous one.
The useReducer hook accepts a reducer function + an initial state. The reducer function is passed the current state and action and returns a new state.
const [state, dispatch] = useReducer(reducer, initialState);
Find in-depth explanations and track study progress here ->
useId hook in React and when should it be used?The useId hook generates unique IDs for elements within a component, which is crucial for accessibility by dynamically creating ids that can be used for linking form inputs and labels. It guarantees unique IDs across the application even if the component renders multiple times.
import { useId } from 'react';function MyComponent() {const id = useId();return (<div><label htmlFor={id}>Name:</label><input id={id} type="text" /></div>);}
Find in-depth explanations and track study progress here ->
To create and use custom hooks in React:
useState or useEffectExample:
function useForm(initialState) {const [formData, setFormData] = useState(initialState);const handleChange = (e) =>setFormData({ ...formData, [e.target.name]: e.target.value });return [formData, handleChange];}
Use the Hook:
function MyForm() {const [formData, handleChange] = useForm({ name: '', email: '' });return <input name="name" value={formData.name} onChange={handleChange} />;}
Custom hooks let you reuse logic across components, keeping your code clean.
Mastering React's advanced concepts like Suspense, forwardRef(), and context demonstrates that you can handle performance optimization, code splitting, and complex component patterns. In interviews, this shows you're prepared to build scalable, maintainable applications beyond just basic component logic.
In React, re-rendering refers to the process of updating the user interface (UI) in response to changes in the component's state or props. When the state or props of a component change, React re-renders the component to reflect the updated data in the UI.
This involves:

Find in-depth explanations and track study progress here ->
forwardRef() in React used for?Before React 19, function components didn't accept ref as a regular prop, so forwardRef() was used to pass a ref through to a child DOM element.
// Pre-React 19import React, { forwardRef } from 'react';const MyComponent = forwardRef((props, ref) => <input ref={ref} {...props} />);
In React 19, ref is a regular prop on function components and forwardRef is deprecated. Destructure it from props:
function MyComponent({ ref, ...props }) {return <input ref={ref} {...props} />;}
Find in-depth explanations and track study progress here ->
Error boundaries catch JavaScript errors in their child components, log them, and display fallback UI instead of crashing the application. They utilize componentDidCatch and static getDerivedStateFromError methods but do not catch errors in event handlers or asynchronous code.
Find in-depth explanations and track study progress here ->
React Suspense allows handling asynchronous operations more elegantly within components. It provides fallback content while waiting for resources like data or code to load. You can use it alongside React.lazy() for code splitting.
const LazyComponent = React.lazy(() => import('./LazyComponent'));function MyComponent() {return (<React.Suspense fallback={<div>Loading...</div>}><LazyComponent /></React.Suspense>);}
Find in-depth explanations and track study progress here ->
Hydration involves attaching event listeners and making server-rendered HTML interactive on the client side. After server-side rendering, React initializes dynamic behavior by attaching event handlers.

Find in-depth explanations and track study progress here ->
React Portals allow rendering children into a DOM node outside the parent component's hierarchy. This is useful for modals or tooltips that need to escape parent overflow or z-index constraints.
Find in-depth explanations and track study progress here ->
React Strict Mode is a development feature in React that activates extra checks and warnings to help identify potential issues in your app.
<React.StrictMode><App /></React.StrictMode>
Wrapping components in <React.StrictMode> activates these development checks without affecting production builds.
Code splitting enhances performance by dividing code into smaller chunks loaded on demand, thereby reducing initial load times. This can be achieved through dynamic import() statements or using React's React.lazy and Suspense.
// Using React.lazy and Suspenseconst LazyComponent = React.lazy(() => import('./LazyComponent'));function App() {return (<React.Suspense fallback={<div>Loading...</div>}><LazyComponent /></React.Suspense>);}
Find in-depth explanations and track study progress here ->
Optimizing context performance involves memoizing context values with useMemo, splitting contexts for isolated state changes, and employing selectors to rerender only necessary components.
const value = useMemo(() => ({ state, dispatch }), [state, dispatch]);
Find in-depth explanations and track study progress here ->
The Flux pattern manages application state through unidirectional data flow, simplifying debugging and enhancing maintainability with clear separation of concerns between Dispatcher, Stores, Actions, and Views.

Find in-depth explanations and track study progress here ->
In React, one-way data flow means data moves from parent to child components through props.
Example:
function Parent() {const [count, setCount] = React.useState(0);return <Child count={count} increment={() => setCount(count + 1)} />;}function Child({ count, increment }) {return <button onClick={increment}>Count: {count}</button>;}
This ensures data flows in one direction, making the app more predictable.

Find in-depth explanations and track study progress here ->
Context in React can lead to performance issues if not handled carefully, causing unnecessary re-renders of components that consume the context, even if only part of the context changes. Overusing context for state management can also make the code harder to maintain and understand. It's best to use context sparingly and consider other state management solutions like Redux or Zustand for more complex scenarios.
Find in-depth explanations and track study progress here ->
React anti-patterns are practices that can lead to inefficient or hard-to-maintain code. Common examples include:
useEffect to derive state from props (compute it during render instead)useReducer or a state libraryuseState for values that don't drive rendering (use useRef instead)The older class-component anti-patterns (using componentWillMount for data fetching or relying on componentWillReceiveProps) refer to APIs that were renamed to UNSAFE_* and no longer apply to function-component code.
Find in-depth explanations and track study progress here ->
Choosing between React state, context, and external state managers depends on your application's complexity. Use React state for local component state, context for global state shared across multiple components, and external managers like Redux or MobX for complex state management requiring advanced features like optimizing re-renders.
Find in-depth explanations and track study progress here ->
setState is called in React?When setState is called in React:
Example:
function Counter() {const [count, setCount] = React.useState(0);const increment = () => {setCount(count + 1); // Calls setState to update state};return <button onClick={increment}>Count: {count}</button>;}
In this example, calling setState (via setCount) triggers a re-render with the updated count.
Prop drilling is when you pass data from a parent component to a deeply nested child component through props, even if intermediate components don't use it.
Example:
function Grandparent() {const data = 'Hello from Grandparent';return <Parent data={data} />;}function Parent({ data }) {return <Child data={data} />;}function Child({ data }) {return <p>{data}</p>;}
In this example, data is passed through multiple components, even though only the Child component uses it. Prop drilling is acceptable for small applications where the component hierarchy is shallow. When global state is needed to be accessed in deeper levels of the app, using context and/or external state managers might be better.
Lazy loading in React is a technique where components are loaded only when they are needed, rather than at the initial page load. This helps reduce the initial load time and improve performance by splitting the code into smaller chunks.
Example:
import React, { Suspense, lazy } from 'react';const LazyComponent = lazy(() => import('./LazyComponent'));function App() {return (<Suspense fallback={<div>Loading...</div>}><LazyComponent /></Suspense>);}
In this example, LazyComponent is loaded only when it's rendered, and while loading, a fallback UI (Loading...) is displayed.
Synthetic events in React are a wrapper around native DOM events that ensure consistent behavior across browsers. They normalize the way events are handled, providing a unified API for React applications.
These events are wrapped in the SyntheticEvent object and expose the usual methods like preventDefault() and stopPropagation(). Since React 17, the root event listener is attached to the React root container (not document), which makes nested React trees work correctly together.
Example:
function MyComponent() {const handleClick = (event) => {event.preventDefault();console.log('Button clicked');};return <button onClick={handleClick}>Click me</button>;}
Older sources mention event pooling, where React reused the event object after the handler ran, which made the event unusable in async code. Event pooling was removed in React 17, so you can read or pass the event object asynchronously without calling event.persist().
Class lifecycle methods only apply to class components, which are no longer the recommended pattern. The function-component equivalents (using useEffect) are shown at the end.
React class components have lifecycle methods for different phases:
constructor: Initializes state or binds methodscomponentDidMount: Runs after the component mounts, useful for API calls or subscriptionscomponentDidMount() {console.log('Component mounted');}
shouldComponentUpdate: Determines if the component should re-rendercomponentDidUpdate: Runs after updates, useful for side effectscomponentWillUnmount: Cleans up (e.g., removing event listeners).componentWillUnmount() {console.log('Component will unmount');}
In function components, all of the above are expressed with useEffect:
useEffect(() => {// componentDidMount + componentDidUpdateconsole.log('Mounted or updated');return () => {// componentWillUnmountconsole.log('Will unmount');};},[/* deps */],);
Concurrent features were introduced in React 18 (the experimental "Concurrent Mode" branding from React 17 is no longer used). They let React pause, interrupt, and resume rendering work instead of running it as a single blocking pass. This keeps the UI responsive: urgent updates like typing or clicks can preempt slower work like rendering a large list or filtering search results.
The features are opt-in via specific APIs (useTransition, useDeferredValue, and <Suspense> for data fetching), not a global mode switch.
React's scheduler assigns priority to updates based on how they're triggered. Updates from direct user interaction (click, input, focus) are treated as urgent and rendered synchronously. Updates wrapped in startTransition or read through useDeferredValue are non-urgent: React can interrupt them to handle a more urgent update, then resume. That's what allows a heavy filter or list render to coexist with typing into a search box without blocking it.
To avoid blocking the UI, use Web Workers, setTimeout, or requestIdleCallback for offloading heavy computations. Alternatively, break tasks into smaller parts and use React's Suspense or useMemo to only recompute when necessary.
Example using setTimeout for deferring computation:
const [data, setData] = useState(null);useEffect(() => {setTimeout(() => {const result = computeExpensiveData();setData(result);}, 0);}, []);
Server-side rendering (SSR) involves rendering components on the server before sending fully rendered HTML to clients, improving initial load times and SEO through efficient hydration processes.

Find in-depth explanations and track study progress here ->
Static generation pre-renders HTML at build time instead of runtime; this approach enhances performance by delivering static content quickly while improving SEO outcomes.
Find in-depth explanations and track study progress here ->
Higher-order components (HOCs) are functions that take a component and return a new one with added props or behavior, facilitating logic reuse across components.
const withExtraProps = (WrappedComponent) => {return (props) => <WrappedComponent {...props} extraProp="value" />;};const EnhancedComponent = withExtraProps(MyComponent);
HOCs were the dominant pattern for cross-cutting logic (auth, data fetching, theming) before hooks. Custom hooks cover almost all of those use cases now without the wrapper-component nesting. HOCs still appear in older codebases and some libraries (e.g., connect from react-redux), but new code should prefer a custom hook.
Find in-depth explanations and track study progress here ->
The presentational vs container pattern split components into two roles: presentational components handled rendering (markup, styling) and received data via props, while container components handled state, data fetching, and behavior, then passed data down.
// Container: handles state/datafunction UserListContainer() {const [users, setUsers] = useState([]);useEffect(() => {fetchUsers().then(setUsers);}, []);return <UserList users={users} />;}// Presentational: pure renderingfunction UserList({ users }) {return (<ul>{users.map((u) => (<li key={u.id}>{u.name}</li>))}</ul>);}
This pattern was popular before hooks; its original author (Dan Abramov) has since said it's no longer worth following as a hard rule. With hooks, the same separation is usually expressed by extracting a custom hook (e.g., useUsers()) rather than a wrapper component. New code typically blends the two roles into a single component plus a custom hook.
Find in-depth explanations and track study progress here ->
Render props in React allow code sharing between components through a prop that is a function. This function returns a React element, enabling data to be passed to child components.
function DataFetcher({ url, render }) {const [data, setData] = useState(null);useEffect(() => {fetch(url).then((res) => res.json()).then(setData);}, [url]);return render(data);}// Usage<DataFetcherurl="/api/data"render={(data) => <div>{data ? data.name : 'Loading...'}</div>}/>;
Like HOCs, render props were a pre-hooks solution for sharing stateful logic. Most of those use cases are now solved with a custom hook (const data = useFetch(url)), which composes more naturally and avoids the render-prop pyramid. Render props are still useful in narrow cases where the consumer needs to control what to render based on parent-managed state (e.g., headless component libraries).
Find in-depth explanations and track study progress here ->
The composition pattern in React involves building components by combining smaller, reusable ones instead of using inheritance. This encourages creating complex UIs by passing components as children or props.
function WelcomeDialog() {return (<Dialog><h1>Welcome</h1><p>Thank you for visiting our spacecraft!</p></Dialog>);}function Dialog(props) {return <div className="dialog">{props.children}</div>;}
Find in-depth explanations and track study progress here ->
To re-render the view on browser resize, use the useEffect hook to listen for the resize event and update state.
Example:
import React, { useState, useEffect } from 'react';function ResizeComponent() {const [windowWidth, setWindowWidth] = useState(window.innerWidth);useEffect(() => {const handleResize = () => setWindowWidth(window.innerWidth);window.addEventListener('resize', handleResize);return () => window.removeEventListener('resize', handleResize);}, []);return <div>Window width: {windowWidth}px</div>;}export default ResizeComponent;
This updates the state and re-renders the component whenever the window is resized.
Asynchronous data loading uses useEffect alongside useState hooks; fetching data inside useEffect updates state with fetched results ensuring re-renders occur with new data.
import React, { useState, useEffect } from 'react';const FetchAndDisplayData = () => {const [info, updateInfo] = useState(null);const [isLoading, toggleLoading] = useState(true);useEffect(() => {const retrieveData = async () => {try {const res = await fetch('https://api.example.com/data');const data = await res.json();updateInfo(data);} catch (err) {console.error('Error fetching data:', err);} finally {toggleLoading(false);}};retrieveData();}, []);return (<div>{isLoading ? (<p>Fetching data, please wait...</p>) : (<pre>{JSON.stringify(info, null, 2)}</pre>)}</div>);};export default FetchAndDisplayData;
Find in-depth explanations and track study progress here ->
Common pitfalls in data fetching with React include failing to handle loading and error states, neglecting to clean up subscriptions which can cause memory leaks, and improperly using lifecycle methods or hooks. Always ensure proper handling of these states, clean up after components, and utilize useEffect for side effects in functional components.
Find in-depth explanations and track study progress here ->
Understanding React Router is important in front end interviews because most real-world applications need client-side routing to handle navigation, dynamic URLs, and nested layouts. Proficiency with routing shows you can structure applications effectively and provide a seamless user experience.
React Router is a popular routing library for React applications that enables navigation between different components based on the URL. It provides declarative routing, allowing you to define routes and their corresponding components in a straightforward manner.
React Router maps URL paths to components, enabling navigation in single-page apps. Dynamic routing allows you to use URL parameters to render components based on dynamic values.
import { BrowserRouter, Routes, Route, useParams } from 'react-router-dom';function UserPage() {const { id } = useParams(); // Access dynamic parameterreturn <h1>User ID: {id}</h1>;}export default function App() {return (<BrowserRouter><Routes><Route path="/user/:id" element={<UserPage />} /> {/* Dynamic path */}</Routes></BrowserRouter>);}
Key features:
:id captures dynamic data from the URL.useParams Hook: Accesses these dynamic values for rendering.Nested routes allow you to create hierarchies of components, and useParams helps access dynamic route parameters.
Key techniques:
<Outlet>: Renders child routes within a parent layoutuseParams: Retrieves route parameters for dynamic routingimport {BrowserRouter,Routes,Route,Outlet,useParams,} from 'react-router-dom';function UserProfile() {const { userId } = useParams();return <h2>User ID: {userId}</h2>;}function App() {return (<BrowserRouter><Routes><Route path="user/:userId" element={<Outlet />}><Route path="profile" element={<UserProfile />} /></Route></Routes></BrowserRouter>);}
BrowserRouter: Uses the HTML5 History API to manage navigation, enabling clean URLs without the hash (#). It requires server-side configuration to handle routes correctly, especially for deep linking.
HashRouter: Uses the hash (#) portion of the URL to simulate navigation. It doesn't require server-side configuration, as the hash is never sent to the server. This makes it suitable for environments where server-side routing isn't possible (e.g., static hosting).
React Router is a routing library for React that provides a declarative API for defining routes and handling navigation. It manages components and URLs.
History library is a lower-level utility that only manages browser history (e.g., pushing and popping history entries). It doesn't handle UI rendering or routing, making it more generic and not React-specific.
React Router uses the history library internally but adds additional features like routing and component management.
<Router> components of React Router v6?In React Router v6, the key <Router> components are:
<BrowserRouter>: Uses the HTML5 history API to keep the UI in sync with the URL. It's commonly used for web applications.<HashRouter>: Uses URL hash fragments (#) to manage routing, making it suitable for static file hosting or legacy browsers that don't support the HTML5 history API.<MemoryRouter>: Keeps the URL in memory (no address bar changes), useful for non-browser environments like tests or embedded apps.<StaticRouter>: Used for server-side rendering (SSR), where routing is handled without a browser, typically in Node.js environments.Each of these routers serves different use cases but provides the same routing functionality within a React app.
The push and replace methods of the history library are used to manage the browser's history stack and control navigation.
push:history.push('/new-page')replace:history.replace('/new-page')In React Router v6, you can navigate programmatically by using the useNavigate hook. First, import useNavigate from react-router-dom and call it to get the navigate function. Then, you can use navigate('/new-page') to navigate to a different route.
For example:
import { useNavigate } from 'react-router-dom';function MyComponent() {const navigate = useNavigate();const goToPage = () => navigate('/new-page');return <button onClick={goToPage}>Go to New Page</button>;}
In React Router v5, the useHistory hook provides access to the history object, which you can use to push a new route. For example, history.push('/new-page') will navigate to the specified route.
For example:
import { useHistory } from 'react-router-dom';function MyComponent() {const history = useHistory();const goToPage = () => history.push('/new-page');return <button onClick={goToPage}>Go to New Page</button>;}
Both methods allow you to navigate programmatically in React Router.
To implement private routes, create a component that checks if the user is authenticated before rendering the desired route.
Example:
import { Navigate } from 'react-router-dom';function PrivateRoute({ children }) {return isAuthenticated ? children : <Navigate to="/login" />;}
PrivateRoute: Checks authentication and either renders the children (protected routes) or redirects to the login page.<Navigate>: Replaces the deprecated <Redirect> for redirecting in React Router v6+.Use the useLocation hook to get the current route, and conditionally apply styles for the active state.
Example:
import { useLocation } from 'react-router-dom';function NavBar() {const location = useLocation();return (<nav><ul><li className={location.pathname === '/home' ? 'active' : ''}>Home</li><li className={location.pathname === '/about' ? 'active' : ''}>About</li></ul></nav>);}
To handle 404 errors or page not found in React Router, create a catch-all route at the end of your route configuration that renders a custom 404 component.
Example:
import { Routes, Route } from 'react-router-dom';function NotFound() {return <h1>404 - Page Not Found</h1>;}function App() {return (<Routes><Route path="/" element={<Home />} /><Route path="/about" element={<About />} /><Route path="*" element={<NotFound />} /></Routes>);}
In this example, the NotFound component is rendered when no other routes match the URL, indicating a 404 error.
In React Router v6, you can use the useSearchParams hook to access query parameters from the URL.
Example:
import { useSearchParams } from 'react-router-dom';function MyComponent() {const [searchParams] = useSearchParams();const queryParam = searchParams.get('paramName');return <div>Query Param: {queryParam}</div>;}
This hook allows you to retrieve and manipulate query parameters in React Router v6.
To perform an automatic redirect after login in React Router, use the useNavigate hook to navigate to the desired route after successful authentication.
Example:
import { useNavigate } from 'react-router-dom';function Login() {const navigate = useNavigate();const handleLogin = () => {// Perform login logicnavigate('/dashboard');};return (<div><button onClick={handleLogin}>Login</button></div>);}
In this example, the handleLogin function navigates to the /dashboard route after successful login.
In React Router v6, you can pass props to a route component using the element prop in the <Route> component.
Example:
import { Routes, Route } from 'react-router-dom';function MyComponent({ propValue }) {return <div>Prop Value: {propValue}</div>;}function App() {return (<Routes><Route path="/my-route" element={<MyComponent propValue="Hello" />} /></Routes>);}
In this example, the propValue prop is passed to the MyComponent component when rendering the /my-route route.
Understanding internationalization (i18n) in React is important in front end interviews because many products serve global audiences and must support multiple languages and locales. Showing you can implement i18n demonstrates attention to accessibility, user experience, and readiness to build applications for diverse users.
Localization typically involves libraries like react-i18next or react-intl. Set up translation files for different languages and configure the library within your app using provided hooks or components.
// Example using react-i18nextimport { useTranslation } from 'react-i18next';const MyComponent = () => {const { t } = useTranslation();return <p>{t('welcome_message')}</p>;};
Find in-depth explanations and track study progress here ->
react-intl?react-intl is a library that provides internationalization (i18n) support for React applications. It helps in formatting numbers, dates, strings, and handling translation/localization. It integrates with the Intl API in JavaScript to provide locale-specific data and translation management.
react-intl?react-intl?<FormattedMessage />, <FormattedNumber />, <FormattedDate />, etc., to format content.useIntl for formatting messages, numbers, or dates imperatively within components.FormattedMessage as a placeholder using react-intl?You can use the FormattedMessage component to handle placeholders within strings. Placeholders are replaced dynamically with variables in the translated string.
import { FormattedMessage } from 'react-intl';function WelcomeMessage() {return (<FormattedMessageid="welcome"defaultMessage="Hello, {name}!"values={{ name: 'John' }}/>);}
Here, {name} is a placeholder, and John will replace it.
You can access the current locale using the useIntl hook or the IntlProvider's locale prop.
Using useIntl:
import { useIntl } from 'react-intl';function LocaleDisplay() {const intl = useIntl();return <div>Current locale: {intl.locale}</div>;}
Using IntlProvider:
<IntlProvider locale="en" messages={messages}><MyComponent /></IntlProvider>
Here, locale="en" defines the current locale.
react-intl?You can format dates using the <FormattedDate /> component or the useIntl hook's formatDate method.
Using <FormattedDate /> component:
import { FormattedDate } from 'react-intl';function DateComponent() {return (<FormattedDatevalue={new Date()}year="numeric"month="long"day="2-digit"/>);}
Using useIntl hook:
import { useIntl } from 'react-intl';function DateComponent() {const intl = useIntl();const formattedDate = intl.formatDate(new Date(), {year: 'numeric',month: 'long',day: '2-digit',});return <div>{formattedDate}</div>;}
These methods allow you to format the date in a locale-sensitive manner.
Understanding testing in React is important in front end interviews because it shows you can write reliable, maintainable code and catch bugs early through unit, integration, and UI tests. Proficiency with tools like Jest and React Testing Library signals that you prioritize code quality and can work effectively in team environments with CI/CD workflows.
Testing React applications can be done using Jest and React Testing Library. Jest serves as the testing framework while React Testing Library provides utilities for testing components similarly to user interactions.
Find in-depth explanations and track study progress here ->
Jest is a JavaScript testing framework that provides a test runner, assertion library, and mocking support. It's commonly used for testing React applications due to its simplicity and integration with tools like React Testing Library.
React Testing Library is a testing utility for React that helps test components in a way that resembles how users interact with the application. It provides functions to render components, interact with them, and assert on the rendered output.
To test React components using React Testing Library, you can:
render.getByText, queryByRole, etc.Example:
import { render, screen, fireEvent } from '@testing-library/react';import MyComponent from './MyComponent';test('renders component', () => {render(<MyComponent />);const button = screen.getByRole('button');fireEvent.click(button);expect(screen.getByText('Clicked!')).toBeInTheDocument();});
In this example, the test renders MyComponent, clicks a button, and asserts that the text 'Clicked!' is present.
To test asynchronous code in React components, you can use async/await with waitFor from React Testing Library to handle asynchronous operations like data fetching or API calls.
Example:
import { render, screen, waitFor } from '@testing-library/react';import MyComponent from './MyComponent';test('fetches data and renders it', async () => {render(<MyComponent />);await waitFor(() => {expect(screen.getByText('Data loaded')).toBeInTheDocument();});});
In this example, the test waits for the data to be loaded before asserting that the text 'Data loaded' is present.
To mock API calls in React component tests, you can use Jest's jest.mock to mock the API module and return mock data. This allows you to simulate API responses without making actual network requests.
Example:
import { render, screen } from '@testing-library/react';jest.mock('./api', () => ({fetchData: jest.fn(() => Promise.resolve('mocked data')),}));import MyComponent from './MyComponent';test('fetches data and renders it', async () => {render(<MyComponent />);expect(screen.getByText('Loading...')).toBeInTheDocument();expect(await screen.findByText('mocked data')).toBeInTheDocument();});
In this example, the fetchData function from the api module is mocked to return 'mocked data' for testing purposes.
Render the hook inside a test using renderHook from @testing-library/react, then call act to drive any state updates.
import { renderHook, act } from '@testing-library/react';import useCounter from './useCounter';test('increments counter', () => {const { result } = renderHook(() => useCounter());act(() => {result.current.increment();});expect(result.current.count).toBe(1);});
Older sources import renderHook from @testing-library/react-hooks. That package was deprecated and merged into @testing-library/react in v13; use the import shown above.
Same approach as above: render the hook with renderHook and assert on result.current. For hooks that depend on context (e.g., a router or theme provider), pass a wrapper option.
import { renderHook, act } from '@testing-library/react';import useCustomHook from './useCustomHook';test('hook behavior', () => {const { result } = renderHook(() => useCustomHook());act(() => {result.current.doSomething();});expect(result.current.value).toBe('expected value');});// With a context provider:const wrapper = ({ children }) => (<MyProvider value="test">{children}</MyProvider>);const { result } = renderHook(() => useCustomHook(), { wrapper });
Shallow rendering renders a component one level deep: its children are not rendered, only referenced as React elements. The intent was to isolate the component under test from its children.
The two implementations were react-test-renderer/shallow (a low-level API) and Enzyme's shallow() (a popular wrapper around it).
// Enzyme-style example (historical)import { shallow } from 'enzyme';const wrapper = shallow(<Button label="Click Me" />);expect(wrapper.text()).toBe('Click Me');
Don't use shallow rendering in new code. Enzyme is unmaintained and has no official React 17+ adapter. The React docs recommend React Testing Library, which renders components the way users see them and asserts on accessible output, so tests don't break on internal refactors. Use RTL's render with screen.getByRole / getByText instead.
Snapshot Testing in React is a testing technique that captures the rendered output of a component and saves it as a snapshot. Subsequent test runs compare the current output with the saved snapshot to detect any unexpected changes. If the output differs from the snapshot, the test fails, indicating that the component's output has changed.
Here's an example of using Snapshot Testing with Jest:
import React from 'react';import renderer from 'react-test-renderer';import MyComponent from './MyComponent';test('renders correctly', () => {const tree = renderer.create(<MyComponent />).toJSON();expect(tree).toMatchSnapshot();});
In this example, the renderer.create function renders the MyComponent and converts it to a JSON tree. The toMatchSnapshot function saves the snapshot of the component's output. Subsequent test runs compare the current output with the saved snapshot, ensuring the component's output remains consistent.
To test React components that use context, you can wrap the component in a context provider with the desired context values for testing. This allows you to simulate the context values and test the component's behavior based on those values.
Example:
import { render } from '@testing-library/react';import { MyContextProvider } from './MyContextProvider';import MyComponent from './MyComponent';test('renders correctly with context', () => {const { getByText } = render(<MyContextProvider value="test value"><MyComponent /></MyContextProvider>,);expect(getByText('test value')).toBeInTheDocument();});
In this example, the MyComponent is wrapped in a MyContextProvider with a specific context value for testing. The test verifies that the component renders correctly with the provided context value.
To test React components that use Redux, you can use the redux-mock-store library to create a mock store with the desired state for testing. This allows you to simulate the Redux store and test the component's behavior based on the state.
Example:
import { render } from '@testing-library/react';import configureStore from 'redux-mock-store';import { Provider } from 'react-redux';import MyComponent from './MyComponent';const mockStore = configureStore([]);test('renders correctly with Redux state', () => {const store = mockStore({ counter: 0 });const { getByText } = render(<Provider store={store}><MyComponent /></Provider>,);expect(getByText('Counter: 0')).toBeInTheDocument();});
In this example, the MyComponent is wrapped in a Provider with a mock Redux store containing the initial state { counter: 0 } for testing. The test verifies that the component renders correctly with the provided Redux state.
react-test-renderer was a utility for rendering React components to a plain JS object tree (rather than the DOM), useful for snapshot testing without a browser environment.
import TestRenderer from 'react-test-renderer';import MyComponent from './MyComponent';const renderer = TestRenderer.create(<MyComponent />);const tree = renderer.toJSON();expect(tree).toMatchSnapshot();
react-test-renderer is deprecated as of React 19, and the React team recommends migrating off it. For component tests, use React Testing Library with a DOM environment (jsdom for Jest, or built-in for Vitest). For snapshot tests, serialize the DOM produced by RTL's render:
import { render } from '@testing-library/react';const { container } = render(<MyComponent />);expect(container).toMatchSnapshot();
React 19 added Actions and form integrations, the use hook, stable Server Components, and the React Compiler. These are common interview topics in 2026.
React 19 adds:
use hook: reads promises and context during render.<form action={fn}>.ref as a regular prop on function components (no more forwardRef).<title>, <meta>, and stylesheets out of JSX.Together, these move data mutations and async UI state into React itself, instead of leaving them as patterns each app reinvents.
By convention, an Action is an async function passed to a React API that runs it inside a transition: useActionState, startTransition (from useTransition), or a <form action={...}> prop. React tracks pending state, surfaces errors, and applies updates inside a transition so the UI stays responsive. This removes the usual boilerplate of toggling a loading flag, wrapping in try/catch, and managing error and data state separately.
import { useActionState } from 'react';async function updateName(prevState, formData) {const name = formData.get('name');const error = await saveName(name);if (error) return { error };return { name };}function NameForm() {const [state, dispatchAction, isPending] = useActionState(updateName, {name: '',});return (<form action={dispatchAction}><input name="name" defaultValue={state.name} /><button disabled={isPending}>Save</button>{state.error && <p>{state.error}</p>}</form>);}
useActionState hook do?useActionState takes an action function and an initial state, and returns [state, dispatchAction, isPending]. Calling dispatchAction (usually by passing it to <form action>) runs the action, marks isPending true, and replaces the state with the action's return value when it resolves. One hook covers what you'd otherwise write as three separate useState calls for data, loading, and error.
useOptimistic do?useOptimistic renders an optimistic version of state immediately while an action is in flight, then automatically reverts to the real state when the action settles. Useful for chat messages, likes, list reordering, or anywhere the network round-trip would feel laggy.
import { useOptimistic } from 'react';function MessageList({ messages, sendMessage }) {const [optimisticMessages, addOptimistic] = useOptimistic(messages,(state, newMessage) => [...state, { text: newMessage, sending: true }],);async function handleSend(formData) {const text = formData.get('text');addOptimistic(text);await sendMessage(text);}return (<>{optimisticMessages.map((m, i) => (<p key={i} style={{ opacity: m.sending ? 0.5 : 1 }}>{m.text}</p>))}<form action={handleSend}><input name="text" /></form></>);}
use hook and how is it different from useEffect + fetch?use reads the value of a Promise or Context during render. When given a Promise, it suspends the component until the promise resolves (handled by the nearest <Suspense> boundary) and then returns the resolved value. Unlike useEffect, use can be called conditionally and inside loops, and the resolved data is available synchronously after suspension, so there's no loading state to thread through the tree.
import { use, Suspense } from 'react';function Profile({ userPromise }) {const user = use(userPromise); // suspends until resolvedreturn <h1>{user.name}</h1>;}// Server Component: render runs once per request, so the promise is stable.// In a Client Component, create the promise outside render (or via `cache()`)// to avoid making a new one on every re-render.async function Page() {const userPromise = fetchUser();return (<Suspense fallback={<p>Loading...</p>}><Profile userPromise={userPromise} /></Suspense>);}
Server Components render on the server and stream their output to the client. They never ship JavaScript to the browser, can await data directly (no useEffect round-trip), and can access server-only resources like the database or filesystem. They cannot use hooks like useState or useEffect, attach event handlers, or use browser-only APIs; those still belong in Client Components (files marked 'use client').
| Server Component | Client Component | |
|---|---|---|
| Where it runs | Server (build or request time) | Browser (after hydration) |
| JS shipped | None | Yes |
| State / effects | Not allowed | Allowed |
| Event handlers | Not allowed | Allowed |
Can await data directly | Yes | No (use use or fetch in effect) |
| Can import the other | Yes (renders Client Components) | No (cannot import Server Components, only receive them as props/children) |
Server Components are typically the outer shell that fetches data; Client Components are the interactive leaves marked with 'use client'.
The React Compiler is an opt-in build-time tool that analyzes your components and automatically inserts memoization equivalent to useMemo, useCallback, and React.memo where it's safe. It removes the need for manual memoization in most cases. It enforces the Rules of React strictly: if your code violates them (e.g., mutating props, calling hooks conditionally), the compiler skips that component instead of producing incorrect output.
useTransition and useDeferredValue?Both mark updates as non-urgent so React can keep the UI responsive. The difference is where you put the control:
useTransition wraps the state setter at the call site. You decide when a particular update should be a transition (e.g., a search submit).useDeferredValue wraps a value at the consumer. It hands you a lagging copy of the value that updates after urgent renders, useful when the data source isn't under your control (e.g., a value coming through props).// useTransition: control at the dispatch siteconst [isPending, startTransition] = useTransition();startTransition(() => setQuery(input));// useDeferredValue: control at the read siteconst deferredQuery = useDeferredValue(query);return <ExpensiveResults query={deferredQuery} />;
action prop work in React 19?React 19 lets you pass a function directly to <form action> (and <button formAction>). React calls the function with a FormData argument when the form is submitted, runs it inside a transition, and resets uncontrolled inputs on success. Combine it with useActionState or useFormStatus for pending state and error handling without manual onSubmit plumbing.
import { useFormStatus } from 'react-dom';function SubmitButton() {const { pending } = useFormStatus();return <button disabled={pending}>{pending ? 'Saving...' : 'Save'}</button>;}function ProfileForm() {async function save(formData) {await updateProfile(Object.fromEntries(formData));}return (<form action={save}><input name="name" /><SubmitButton /></form>);}
These 100+ questions should give you a good idea on what to expect in React interviews. If you're looking for more in-depth React interview preparation materials, check out these:
You can also explore the Top ReactJS Interview Questions repo - a collection of 50 commonly asked questions compiled from real interview experiences.

JavaScript is an essential skill for anyone pursuing a career in web development, but securing a job in this field can be particularly challenging for newcomers. A critical part of the hiring process is the technical interview, where your JavaScript expertise will be thoroughly evaluated.
To support your preparation and build your confidence, we've put together a list of the top 75+ must-know JavaScript interview questions and answers frequently encountered in interviews.
What's new in the May 2026 update
- 25 new questions on modern JavaScript: optional chaining, nullish coalescing,
Promise.allSettled/Promise.any,AbortController, generators,error.cause, immutable array methods (toSorted/toReversed),Object.groupBy, Setunion/intersection/difference, iterator helpers,structuredClone, private class fields, and more; see the Modern JavaScript (ES2020+) section below.
If you're looking for additional JavaScript interview preparation materials, also check out these resources:
Debouncing is a smart way to handle events that fire repeatedly within a short time, such as typing in a search box or resizing a window. Instead of executing a function every single time the event is triggered, debouncing ensures the function runs only after the event stops firing for a specified time.
It prevents performance bottlenecks by reducing the number of unnecessary function calls, making your app smoother and more efficient.
The debounce method delays a function's execution until after a defined "waiting period" has passed since the last event. Let's see an example using Lodash:
import { debounce } from 'lodash';const searchInput = document.getElementById('search-input');const debouncedSearch = debounce(() => {// Perform the search operation hereconsole.log('Searching for:', searchInput.value);}, 300);searchInput.addEventListener('input', debouncedSearch);
While debouncing waits until user activity stops, throttling ensures the function runs at fixed intervals, regardless of how often the event occurs. Each technique suits specific use cases, such as search boxes (debouncing) versus scroll events (throttling).
Practice implementing a Debounce function on GreatFrontEnd ->
Promise.all()Promise.all() is a powerful method in JavaScript that allows you to handle multiple asynchronous tasks simultaneously. It takes an array of promises and returns a single promise that resolves when all the promises resolve, or rejects if any one of them fails.
This method is perfect when you need to wait for several independent asynchronous tasks to finish before proceeding, like fetching data from multiple APIs.
Here's how Promise.all() works with multiple API requests:
const promise1 = fetch('https://api.example.com/data/1');const promise2 = fetch('https://api.example.com/data/2');const promise3 = fetch('https://api.example.com/data/3');Promise.all([promise1, promise2, promise3]).then((responses) => {// Executes only when all promises are resolved.console.log('All responses:', responses);}).catch((error) => {// Catches any error from any promise.console.error('Error:', error);});
Promise.allPractice implementing a Promise.all function on GreatFrontEnd ->
Deep equality involves comparing two objects or arrays to determine if they are structurally identical. Unlike shallow equality, which only checks if object references are the same, deep equality examines whether all nested values are equal.
Here's a simple deepEqual implementation:
function deepEqual(obj1, obj2) {if (obj1 === obj2) return true;if (obj1 == null ||typeof obj1 !== 'object' ||obj2 == null ||typeof obj2 !== 'object')return false;let keys1 = Object.keys(obj1);let keys2 = Object.keys(obj2);if (keys1.length !== keys2.length) return false;for (let key of keys1) {if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) return false;}return true;}// Example usageconst object1 = {name: 'John',age: 30,address: {city: 'New York',zip: '10001',},};const object2 = {name: 'John',age: 30,address: {city: 'New York',zip: '10001',},};console.log(deepEqual(object1, object2)); // true
This function uses recursion to check nested properties, ensuring all values match in both objects or arrays. It's a critical concept for comparing complex data structures in frontend development.
Practice implementing Deep Equal on GreatFrontEnd ->
An EventEmitter is a utility that enables objects to listen for and emit events. It implements the observer pattern, allowing you to subscribe to actions or changes and handle them when triggered. This concept is fundamental in both JavaScript and Node.js for managing event-driven programming.
const eventEmitter = new EventEmitter();// Subscribe to an eventeventEmitter.on('customEvent', (data) => {console.log('Event emitted with data:', data);});// Emit the eventeventEmitter.emit('customEvent', { message: 'Hello, world!' });
EventEmitter allows flexible communication between components, making it useful in scenarios like state management, logging, or real-time updates.
Practice implementing an Event Emitter on GreatFrontEnd ->
Array.prototype.reduce()?Array.prototype.reduce() is a versatile method for iterating through an array and reducing it to a single value. It processes each element with a callback function, carrying over an accumulator to build the final result. Common use cases include summing numbers, flattening arrays, or even building complex objects.
const numbers = [1, 2, 3, 4, 5];const sum = numbers.reduce(function (accumulator, currentValue) {return accumulator + currentValue;}, 0);console.log(sum); // Output: 15
reduce?Practice implementing Array.protoype.reduce on GreatFrontEnd ->
Flattening transforms a nested array into a single-level array, making it more manageable. Since ES2019, JavaScript provides the Array.prototype.flat() method for this.
const nestedArray = [1, [2, [3, [4, [5]]]]];const flatArray = nestedArray.flat(Infinity);console.log(flatArray); // Output: [1, 2, 3, 4, 5]
Here, .flat(Infinity) ensures the entire array is flattened, no matter how deep. For less deeply nested arrays, you can specify the depth.
Before ES2019, custom solutions were common:
// Custom recursive array flattenerfunction flattenArray(arr) {return arr.reduce((acc, val) =>Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val),[],);}const nestedArray = [1, [2, [3, [4, [5]]]]];const flatArray = flattenArray(nestedArray);console.log(flatArray); // Output: [1, 2, 3, 4, 5]
Practice implementing a flatten function on GreatFrontEnd ->
Merging data is crucial when handling complex structures. JavaScript provides efficient ways to combine objects or arrays.
The spread operator is concise and intuitive for merging objects:
const obj1 = { a: 1, b: 2 };const obj2 = { b: 3, c: 4 };const mergedObj = { ...obj1, ...obj2 };console.log(mergedObj); // Output: { a: 1, b: 3, c: 4 }
Object.assign()Another approach is Object.assign():
const obj1 = { a: 1, b: 2 };const obj2 = { b: 3, c: 4 };const mergedObj = Object.assign({}, obj1, obj2);console.log(mergedObj); // Output: { a: 1, b: 3, c: 4 }
const array1 = [1, 2, 3];const array2 = [4, 5, 6];const mergedArray = [...array1, ...array2];console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
Array.concat()const array1 = [1, 2, 3];const array2 = [4, 5, 6];const mergedArray = array1.concat(array2);console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
For nested objects, you'll need custom logic or libraries:
function deepMerge(target, source) {for (const key in source) {if (source[key] instanceof Object && key in target) {Object.assign(source[key], deepMerge(target[key], source[key]));}}Object.assign(target || {}, source);return target;}const obj1 = { a: 1, b: { x: 10, y: 20 } };const obj2 = { b: { y: 30, z: 40 }, c: 3 };const mergedObj = deepMerge(obj1, obj2);console.log(mergedObj); // Output: { a: 1, b: { x: 10, y: 30, z: 40 }, c: 3 }
Alternatively, libraries like Lodash simplify deep merging:
const _ = require('lodash');const obj1 = { a: 1, b: { x: 10, y: 20 } };const obj2 = { b: { y: 30, z: 40 }, c: 3 };const mergedObj = _.merge({}, obj1, obj2);console.log(mergedObj); // Output: { a: 1, b: { x: 10, y: 30, z: 40 }, c: 3 }
Practice implementing a deep merge function on GreatFrontEnd ->
getElementsByClassNamegetElementsByClassName fetches elements matching a specific class and returns them as a live HTMLCollection.
// Fetch and loop through elementsconst elements = document.getElementsByClassName('example');for (let i = 0; i < elements.length; i++) {console.log(elements[i].textContent);}
You can combine class names for more specific selections:
const elements = document.getElementsByClassName('class1 class2');
HTMLCollection updates automatically if DOM elements are added or removed.
For more complex selectors, use querySelectorAll:
const elements = document.querySelectorAll('.example');
Practice Using getElementsByClassName on GreatFrontEnd ->
Memoization saves computed results to avoid redundant calculations.
function expensiveOperation(n) {console.log('Calculating for', n);return n * 2;}// Memoize functionfunction memoize(func) {const cache = {};return function (n) {if (cache[n] !== undefined) {console.log('From cache for', n);return cache[n];}const result = func(n);cache[n] = result;return result;};}const memoizedExpensiveOperation = memoize(expensiveOperation);console.log(memoizedExpensiveOperation(5)); // Calculating for 5, 10console.log(memoizedExpensiveOperation(5)); // From cache for 5, 10
Libraries like Lodash also provide a memoize utility.
Practice implementing a memoize function on GreatFrontEnd ->
getAccessing nested object properties risk errors if any property is undefined. Tools like Lodash's get or JavaScript's optional chaining (?.) help mitigate this.
const user = { address: { city: 'New York' } };console.log(_.get(user, 'address.city')); // 'New York'console.log(user.address?.city); // 'New York'
These methods safely retrieve nested properties without crashing the program.
Practice implementing a get function on GreatFrontEnd ->
Hoisting refers to how JavaScript moves variable and function declarations to the top of their scope during compilation. While only the declaration is hoisted (not the initialization), understanding hoisting helps in writing cleaner and bug-free code.
varVariables declared with var are hoisted and initialized as undefined. Accessing them before initialization results in undefined.
console.log(foo); // undefinedvar foo = 1;console.log(foo); // 1
let, const, and classVariables declared with let, const, and class are hoisted but exist in a "temporal dead zone" until their declaration is reached, causing a ReferenceError if accessed early.
console.log(y); // ReferenceErrorlet y = 'local';
Both the declaration and definition of functions are hoisted, allowing them to be called before their declaration.
foo(); // 'FOOOOO'function foo() {console.log('FOOOOO');}
For function expressions, only the variable is hoisted, not the function itself.
console.log(bar); // undefinedbar(); // TypeError: bar is not a functionvar bar = function () {console.log('BARRRR');};
Imports are hoisted, making them available throughout the module. However, their initialization happens before the module code executes.
foo.doSomething(); // Works fineimport foo from './modules/foo';
Modern JavaScript uses let and const to avoid hoisting pitfalls. Declare variables at the top of their scope for better readability and use tools like ESLint to enforce best practices:
By following these practices, you can write robust, maintainable code.
Read more about the concept of "Hoisting" on GreatFrontEnd ->
let, var, and const?In JavaScript, let, var, and const are used to declare variables, but they differ in scope, initialization, redeclaration, reassignment, and behavior when accessed before declaration.
Variables declared with var are function-scoped or global, while let and const are block-scoped (confined to the nearest {} block).
if (true) {var foo = 1;let bar = 2;const baz = 3;}console.log(foo); // 1console.log(bar); // ReferenceErrorconsole.log(baz); // ReferenceError
var and let can be declared without initialization, but const requires an initial value.
var a; // Validlet b; // Validconst c; // SyntaxError: Missing initializer
Variables declared with var can be redeclared, but let and const cannot.
var x = 10;var x = 20; // Allowedlet y = 10;let y = 20; // SyntaxError: Identifier 'y' has already been declared
var and let allow reassignment, while const does not.
let a = 1;a = 2; // Allowedconst b = 1;b = 2; // TypeError: Assignment to constant variable
All variables are hoisted, but var initializes to undefined, whereas let and const exist in a "temporal dead zone" until the declaration is reached.
console.log(foo); // undefinedvar foo = 'foo';console.log(bar); // ReferenceErrorlet bar = 'bar';
const for variables that don't change to ensure immutability.let when reassignment is needed.var due to its hoisting and scoping issues.Read more about the differences between let, var, and const on GreatFrontEnd ->
== and === in JavaScript?The == operator checks for equality after performing type conversion, while === checks for strict equality without type conversion.
==)== allows type coercion, which means JavaScript converts values to the same type before comparison. This can lead to unexpected results.
42 == '42'; // true0 == false; // truenull == undefined; // true
===)=== checks both value and type, avoiding the pitfalls of type coercion.
42 === '42'; // false0 === false; // falsenull === undefined; // false
=== for most comparisons as it avoids implicit type conversion and makes code more predictable.== only when comparing null or undefined for simplicity.let x = null;console.log(x == null); // trueconsole.log(x == undefined); // true
Object.is()Object.is() is similar to === but treats -0 and +0 as distinct and considers NaN equal to itself.
console.log(Object.is(-0, +0)); // falseconsole.log(Object.is(NaN, NaN)); // true
=== for strict comparisons to avoid bugs caused by type coercion.Object.is() for nuanced comparisons like distinguishing -0 and +0.Explore the differences between == and === on GreatFrontEnd ->
The event loop is the backbone of JavaScript's asynchronous behavior, enabling single-threaded execution without blocking.
setTimeout and HTTP requests on separate threadssetTimeout and UI eventsPromise callbacks, executed before macrotasksconsole.log('Start');setTimeout(() => console.log('Timeout 1'), 0);Promise.resolve().then(() => console.log('Promise 1'));setTimeout(() => console.log('Timeout 2'), 0);console.log('End');
Output:
StartEndPromise 1Timeout 1Timeout 2
Explanation:
Start, End) run first.Promise 1) follow.Timeout 1, Timeout 2) run last.Explore the event loop in JavaScript on GreatFrontEnd ->
Event delegation is an efficient way to manage events for multiple elements by attaching a single event listener to their common parent.
event.target to determine the clicked element.// HTML:// <ul id="item-list">// <li>Item 1</li>// <li>Item 2</li>// </ul>const itemList = document.getElementById('item-list');itemList.addEventListener('click', (event) => {if (event.target.tagName === 'LI') {console.log(`Clicked on ${event.target.textContent}`);}});
Explore event delegation in JavaScript on GreatFrontEnd ->
this works in JavaScriptThe value of this depends on how a function is called. Let's explore its different behaviors.
Using new: When creating objects, this refers to the newly created object.
function Person(name) {this.name = name;}const person = new Person('Alice');console.log(person.name); // 'Alice'
Using apply, call, or bind: Explicitly sets this to a specified object.
function greet() {console.log(this.name);}const person = { name: 'Alice' };greet.call(person); // 'Alice'
Method call: this refers to the object the method is called on.
const obj = {name: 'Alice',greet() {console.log(this.name);},};obj.greet(); // 'Alice'
Free function call: Defaults to the global object (window in browsers) or undefined in strict mode.
function greet() {console.log(this); // global object or undefined}greet();
Arrow functions: Capture this from their enclosing scope.
const obj = {name: 'Alice',greet: () => {console.log(this.name); // Inherits `this` from enclosing scope},};obj.greet(); // undefined
thisArrow functions simplify usage by capturing this from their lexical scope.
function Timer() {this.seconds = 0;setInterval(() => {this.seconds++;console.log(this.seconds);}, 1000);}const timer = new Timer();
Explore how this works in JavaScript on GreatFrontEnd ->
sessionStorage, and localStorage apart?When it comes to client-side storage, cookies, localStorage, and sessionStorage serve distinct roles:
// Set a cookie with an expiry datedocument.cookie = 'userId=12345; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/';// Read all cookiesconsole.log(document.cookie);// Delete a cookiedocument.cookie = 'userId=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
localStorage// Store data in localStoragelocalStorage.setItem('username', 'john_doe');// Retrieve dataconsole.log(localStorage.getItem('username'));// Remove an itemlocalStorage.removeItem('username');// Clear all localStorage datalocalStorage.clear();
sessionStoragelocalStorage (around 5MB).// Store data in sessionStoragesessionStorage.setItem('sessionId', 'abcdef');// Retrieve dataconsole.log(sessionStorage.getItem('sessionId'));// Remove an itemsessionStorage.removeItem('sessionId');// Clear all sessionStorage datasessionStorage.clear();
Learn more about cookies, sessionStorage, and localStorage on GreatFrontEnd ->
<script>, <script async>, and <script defer> differ?<script>When using the <script> tag without attributes, it fetches and executes the script immediately, pausing HTML parsing.
Use case: Critical scripts needed before page rendering.
<script src="main.js"></script>
<script async>With async, the script loads in parallel to HTML parsing and executes as soon as it's ready.
Use case: Independent scripts like analytics or ads.
<script async src="analytics.js"></script>
<script defer>When using defer, the script loads alongside HTML parsing but only executes after the HTML is fully parsed.
Use Case: Scripts that rely on a complete DOM structure.
<script defer src="deferred.js"></script>
Discover more about <script>, <script async>, and <script defer> on GreatFrontEnd ->
null, undefined?Variables not defined using var, let, or const are considered undeclared and can cause global scope issues.
undefinedA declared variable that hasn't been assigned a value is undefined.
nullRepresents the intentional absence of any value. It's an explicit assignment. Example Code:
let a;console.log(a); // undefinedlet b = null;console.log(b); // nulltry {console.log(c); // ReferenceError: c is not defined} catch (e) {console.log('c is undeclared');}
Read more about null, undefined, and undeclared variables on GreatFrontEnd ->
.call() vs .apply()?Both .call and .apply let you invoke a function with a specified this value. The key difference lies in how arguments are passed:
.call: Accepts arguments as a comma-separated list..apply: Accepts arguments as an array.Memory aid:
function sum(a, b) {return a + b;}console.log(sum.call(null, 1, 2)); // 3console.log(sum.apply(null, [1, 2])); // 3
Learn more about .call and .apply on GreatFrontEnd ->
Function.prototype.bind work?The bind method is used to create a new function with a specific this value and, optionally, preset arguments. This ensures that the function always has the correct this context, regardless of how or where it's called.
bind:this is correctly set for the function.const john = {age: 42,getAge: function () {return this.age;},};console.log(john.getAge()); // 42const unboundGetAge = john.getAge;console.log(unboundGetAge()); // undefinedconst boundGetAge = john.getAge.bind(john);console.log(boundGetAge()); // 42const mary = { age: 21 };const boundGetAgeMary = john.getAge.bind(mary);console.log(boundGetAgeMary()); // 21
Explore Function.prototype.bind on GreatFrontEnd ->
Using arrow functions for methods in constructors automatically binds the this context to the constructor, avoiding the need to manually bind it. This eliminates issues caused by this referring to unexpected contexts.
const Person = function (name) {this.name = name;this.sayName1 = function () {console.log(this.name);};this.sayName2 = () => {console.log(this.name);};};const john = new Person('John');const dave = new Person('Dave');john.sayName1(); // Johnjohn.sayName2(); // Johnjohn.sayName1.call(dave); // Davejohn.sayName2.call(dave); // John
Arrow functions are particularly useful in React class components, ensuring methods maintain the correct context when passed to child components.
Explore the advantage for using the arrow syntax for a method in a constructor on GreatFrontEnd ->
Prototypal inheritance is a way for objects to share properties and methods through their prototype chain.
null.new to create objects.function Animal(name) {this.name = name;}Animal.prototype.sayName = function () {console.log(`My name is ${this.name}`);};function Dog(name, breed) {Animal.call(this, name);this.breed = breed;}Dog.prototype = Object.create(Animal.prototype);Dog.prototype.bark = function () {console.log('Woof!');};let fido = new Dog('Fido', 'Labrador');fido.bark(); // "Woof!"fido.sayName(); // "My name is Fido"
Explore how prototypal inheritance works on GreatFrontEnd ->
function Person(){}, const person = Person(), and const person = new Person()?function Person(){}: A function declaration, typically used for constructors if written in PascalCase.const person = Person(): Calls the function normally and assigns the result to person. No object creation happens unless explicitly returned.const person = new Person(): Invokes the function as a constructor, creating a new object and setting its prototype to Person.prototype.function foo() {}foo(); // "Hello!"function foo() {console.log('Hello!');}
var foo = function() {}foo(); // TypeError: foo is not a functionvar foo = function () {console.log('Hello!');};
Here are various approaches to creating objects in JavaScript:
Object literals: The simplest and most common way to create an object is using curly braces {} with key-value pairs.
const person = {firstName: 'John',lastName: 'Doe',};
Object constructor: Use the built-in Object constructor with the new keyword.
const person = new Object();person.firstName = 'John';person.lastName = 'Doe';
Object.create() method: Create an object with a specific prototype.
const personPrototype = {greet() {console.log(`Hello, my name is ${this.name}.`);},};const person = Object.create(personPrototype);person.name = 'John';person.greet(); // Hello, my name is John.
ES2015 classes: Define objects using the class syntax for a blueprint-like structure.
class Person {constructor(name, age) {this.name = name;this.age = age;}greet() {console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);}}const john = new Person('John', 30);john.greet(); // Hi, I'm John and I'm 30 years old.
Constructor functions: Use a function as a template for creating multiple objects.
function Person(name, age) {this.name = name;this.age = age;}const john = new Person('John', 30);console.log(john.name); // John
Explore various ways to create objects in JavaScript on GreatFrontEnd ->
A higher-order function is a function that either:
Accepts another function as an argument:
function greet(name) {return `Hello, ${name}!`;}function greetUser(greeter, name) {console.log(greeter(name));}greetUser(greet, 'Alice'); // Hello, Alice!
Returns another function:
function multiplier(factor) {return function (num) {return num * factor;};}const double = multiplier(2);console.log(double(4)); // 8
Explore the definition of a higher-order function on GreatFrontEnd ->
ES5 constructor functions use function constructors and prototypes for object creation and inheritance.
function Person(name, age) {this.name = name;this.age = age;}Person.prototype.greet = function () {console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);};const john = new Person('John', 30);john.greet(); // Hi, I'm John and I'm 30 years old.
ES2015 Classes use the class keyword for cleaner and more intuitive syntax.
class Person {constructor(name, age) {this.name = name;this.age = age;}greet() {console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);}}const john = new Person('John', 30);john.greet(); // Hi, I'm John and I'm 30 years old.
static in ES2015.extends and super keywords in ES2015.Explore differences between ES2015 classes and ES5 constructor functions on GreatFrontEnd ->
Event bubbling is the process where an event triggers on the target element and then propagates upwards through its ancestors in the DOM.
const parent = document.getElementById('parent');const child = document.getElementById('child');parent.addEventListener('click', () => {console.log('Parent clicked');});child.addEventListener('click', () => {console.log('Child clicked');});
Clicking the child element will log both "Child clicked" and "Parent clicked" due to bubbling.
Use event.stopPropagation() to prevent the event from propagating upwards.
child.addEventListener('click', (event) => {event.stopPropagation();console.log('Child clicked only');});
Explore event bubbling on GreatFrontEnd ->
Event capturing, also called "trickling", is the reverse of bubbling. The event propagates from the root element down to the target element.
Capturing is enabled by passing { capture: true } to addEventListener() as the third argument.
const parent = document.getElementById('parent');const child = document.getElementById('child');parent.addEventListener('click',() => {console.log('Parent capturing');},{ capture: true },);child.addEventListener('click', () => {console.log('Child clicked');});
Clicking the child will log "Parent capturing" first, followed by "Child clicked".
Explore event capturing on GreatFrontEnd ->
mouseenter and mouseover differ?mouseentermouseoverExplore the differences between mouseenter and mouseover on GreatFrontEnd ->
const fs = require('fs');const data = fs.readFileSync('file.txt', 'utf8');console.log(data); // Blocks until the file is fully readconsole.log('Program ends');
console.log('Start');fetch('https://api.example.com/data').then((response) => response.json()).then((data) => console.log(data)) // Non-blocking.catch((error) => console.error(error));console.log('End');
Explore the difference between synchronous and asynchronous functions on GreatFrontEnd ->
AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to fetch and send data asynchronously, enabling dynamic updates without reloading the entire page.
XMLHttpRequest; fetch() is the modern alternative.XMLHttpRequest:let xhr = new XMLHttpRequest();xhr.onreadystatechange = function () {if (xhr.readyState === XMLHttpRequest.DONE) {if (xhr.status === 200) {console.log(xhr.responseText);} else {console.error('Request failed');}}};xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);xhr.send();
fetch():fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) => response.json()).then((data) => console.log(data)).catch((error) => console.error('Fetch error:', error));
Explore AJAX in detail on GreatFrontEnd ->
Explore the advantages and disadvantages of using AJAX on GreatFrontEnd ->
XMLHttpRequest and fetch()?XMLHttpRequestonprogress.onerror event.let xhr = new XMLHttpRequest();xhr.open('GET', 'https://example.com/api', true);xhr.onload = function () {if (xhr.status === 200) {console.log(xhr.responseText);}};xhr.send();
fetch().catch() for better error management.AbortController for cancellations.fetch('https://example.com/api').then((response) => response.json()).then((data) => console.log(data)).catch((error) => console.error(error));
fetch() has cleaner syntax and better Promise integration.XMLHttpRequest supports progress tracking, which fetch() does not.Explore the differences between XMLHttpRequest and fetch() on GreatFrontEnd ->
JavaScript features a mix of primitive and non-primitive (reference) data types.
true or false.Tip: Use the typeof operator to determine the type of a variable.
Explore the various data types in JavaScript on GreatFrontEnd ->
JavaScript provides multiple ways to iterate over objects and arrays.
for...inLoops over all enumerable properties, including inherited ones.
for (const property in obj) {if (Object.hasOwn(obj, property)) {console.log(property);}}
Object.keys()Retrieves an array of an object's own enumerable properties.
Object.keys(obj).forEach((key) => console.log(key));
Object.entries()Returns an array of [key, value] pairs.
Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`));
Object.getOwnPropertyNames()Includes both enumerable and non-enumerable properties.
Object.getOwnPropertyNames(obj).forEach((prop) => console.log(prop));
for LoopClassic approach for iterating through arrays:
for (let i = 0; i < arr.length; i++) {console.log(arr[i]);}
Array.prototype.forEach()Executes a callback for each array item.
arr.forEach((element, index) => console.log(element, index));
for...ofIdeal for looping through iterable objects like arrays.
for (const element of arr) {console.log(element);}
Array.prototype.entries()Iterates with both index and value.
for (const [index, element] of arr.entries()) {console.log(index, ':', element);}
Explore iteration techniques on GreatFrontEnd ->
...)The spread operator is used to expand elements of arrays or objects.
Copying arrays/objects:
const array = [1, 2, 3];const newArray = [...array]; // [1, 2, 3]
Merging arrays/objects:
const arr1 = [1, 2];const arr2 = [3, 4];const mergedArray = [...arr1, ...arr2]; // [1, 2, 3, 4]
Passing function arguments:
const nums = [1, 2, 3];console.log(Math.max(...nums)); // 3
...)The rest operator collects multiple elements into an array or object.
Function parameters:
function sum(...numbers) {return numbers.reduce((a, b) => a + b);}sum(1, 2, 3); // 6
Destructuring:
const [first, ...rest] = [1, 2, 3];console.log(rest); // [2, 3]
Explore spread and rest syntax on GreatFrontEnd ->
Mapsize property.const map = new Map();map.set('key', 'value');console.log(map.size); // 1
Object.keys(), Object.values(), or Object.entries().size property.const obj = { key: 'value' };console.log(Object.keys(obj).length); // 1
Explore the difference between Map and plain objects on GreatFrontEnd ->
Map/Set and WeakMap/WeakSetWeakMap and WeakSet keys must be objects, while Map and Set accept any data type.WeakMap and WeakSet allow garbage collection of keys, making them useful for managing memory.Map and Set have a size property.WeakMap and WeakSet are not iterable.// Map Exampleconst map = new Map();map.set({}, 'value');console.log(map.size); // 1// WeakMap Exampleconst weakMap = new WeakMap();let obj = {};weakMap.set(obj, 'value');obj = null; // Key is garbage-collected
Explore the differences between Map/Set and WeakMap/WeakSet on GreatFrontEnd ->
Arrow functions simplify function syntax, making them ideal for inline callbacks.
// Traditional function syntaxconst numbers = [1, 2, 3, 4, 5];const doubledNumbers = numbers.map(function (number) {return number * 2;});console.log(doubledNumbers); // [2, 4, 6, 8, 10]// Arrow function syntaxconst doubledWithArrow = numbers.map((number) => number * 2);console.log(doubledWithArrow); // [2, 4, 6, 8, 10]
Explore a use case for the new arrow function syntax on GreatFrontEnd ->
A callback is a function passed as an argument to another function, executed after the completion of an asynchronous task.
function fetchData(callback) {setTimeout(() => {const data = { name: 'John', age: 30 };callback(data);}, 1000);}fetchData((data) => {console.log(data); // { name: 'John', age: 30 }});
Explore the concept of a callback function in asynchronous operations on GreatFrontEnd ->
Debouncing delays execution of a function until a specified time has elapsed since its last invocation.
function debounce(func, delay) {let timeoutId;return (...args) => {clearTimeout(timeoutId);timeoutId = setTimeout(() => func.apply(this, args), delay);};}
Throttling ensures a function executes at most once within a set time interval.
function throttle(func, limit) {let inThrottle;return (...args) => {if (!inThrottle) {func.apply(this, args);inThrottle = true;setTimeout(() => (inThrottle = false), limit);}};}
Explore the concept of debouncing and throttling on GreatFrontEnd ->
Destructuring simplifies extracting values from arrays or objects into individual variables.
// Array destructuringconst [a, b] = [1