React 19 • TypeScript • Next.js • Angular 19
React 19, Angular 19, TypeScript & Frontend Machine Coding Interview Questions (2026)
Prepare for Product Startups, MNCs & GCC UI rounds with real JavaScript Event Loop/V8 internals, Polyfills, React 19 Concurrent rendering, Angular 19 Signals, Web Performance (INP/LCP), and RADIO Frontend System Design.
Freshers JavaScript Internals Q1. Explain the JavaScript Event Loop, Microtask Queue, and Macrotask Queue execution order.
JavaScript executes synchronous code on the Call Stack first. Once the stack empties, the Event Loop drains ALL queued Microtasks (Promise .then/.catch/.finally, queueMicrotask, MutationObserver) completely before picking a single Macrotask (setTimeout, setInterval, I/O, UI events) and running browser rendering frames (requestAnimationFrame). Starving microtasks via recursive Promises freezes UI rendering.
Freshers JS Polyfills Q2. What is the difference between Debounce and Throttle, and where is each used in real UIs?
Debounce delays invoking a function until a quiet period has elapsed after the last event (ideal for search-box autocomplete API calls or form validation). Throttle guarantees the function runs at most once per fixed time interval regardless of event bursts (ideal for scroll position tracking, window resize layout recalculations, or button spam prevention).
Freshers React Fundamentals Q3. Why should you never use array index as a React key in dynamic lists?
React’s Fiber reconciliation matches old and new elements by key to preserve DOM nodes and component state. When items are inserted, deleted, or reordered, array indices shift across different items — causing mismatched controlled inputs, broken animations, and unnecessary re-renders. Always use stable unique domain IDs.
Freshers TypeScript 5 Q4. How do TypeScript Discriminated Unions prevent impossible UI states?
Instead of messy boolean flags (isLoading, isError, data) that allow invalid combinations like loading+error simultaneously, model API state as a discriminated union: { status: "loading" } | { status: "error"; message: string } | { status: "success"; data: User[] }. TypeScript exhaustively narrows properties inside switch(state.status), eliminating runtime undefined crashes.
Freshers CSS & Layout Q5. When should you use CSS Grid vs Flexbox, and how do CSS Container Queries (@container) help component libraries?
Use Flexbox for one-dimensional alignment along a single row or column (navbars, button strips, badge wraps) and CSS Grid for two-dimensional tracks (dashboards, card matrices, asymmetric page shells). Container Queries (@container) let a reusable widget adapt its layout to its parent container width rather than the global viewport — essential for sidebar vs main-area cards.
Experienced React 19 Architecture Q6. How do React 19 Transitions (useTransition) and useOptimistic improve perceived INP responsiveness?
useTransition marks non-urgent state updates (like filtering a 5,000-row table or switching heavy tabs) as interruptible so high-priority user typing/clicks stay responsive without blocking the main thread. useOptimistic immediately reflects an expected mutation in the UI while an async Server Action or fetch is in flight, automatically rolling back if the request fails.
Experienced State Management Q7. When should you use TanStack Query vs Redux Toolkit vs React Context?
Use TanStack Query for Server State (caching, request deduplication, background refetching, pagination, optimistic mutations). Use Redux Toolkit (or Zustand) for complex cross-page Client State (multi-step checkout cart, undo/redo editor, feature workspace). Reserve React Context for low-frequency dependency injection (theme, auth user, locale) because every context value change re-renders all consumers.
Experienced Angular 19 Enterprise Q8. How do Angular 19 Signals and Zoneless Change Detection outperform Zone.js dirty checking?
Zone.js monkey-patches browser async APIs and triggers top-down component tree checks even when a tiny nested state changed. Angular Signals form a fine-grained reactive dependency graph (signal, computed, effect) that notifies ONLY the exact views reading a modified signal — cutting bundle overhead, removing Zone.js patching bugs, and slashing INP frame time.
Experienced RxJS Operators Q9. Compare switchMap, mergeMap, concatMap, and exhaustMap in Angular HTTP workflows.
switchMap cancels previous in-flight inner observables when a new emission arrives (best for live typeahead search). concatMap queues requests strictly sequentially preserving order (best for ordered writes). mergeMap runs all inner requests in parallel (best for independent batch deletes). exhaustMap ignores new clicks while a request is active (best for login/payment submit buttons preventing duplicate calls).
Experienced Next.js App Router Q10. What is the difference between React Server Components (RSC) and Client Components, and what causes Hydration Mismatches?
Server Components run exclusively on the server, never ship their JS code to the browser, and can directly query DBs/APIs; Client Components ("use client") hydrate in the browser for interactivity, hooks, and DOM events. Hydration mismatches happen when initial client render differs from server HTML (e.g., reading window, Date.now(), Math.random(), or localStorage directly during render instead of inside useEffect).
System Design Machine Coding Q11. How do you handle race conditions in a React/JS Autocomplete Search widget?
Combine three defenses: (1) Debounce keystrokes (250–300ms), (2) attach an AbortController signal to every fetch and call controller.abort() inside cleanup before firing a newer request, and (3) cache results by normalized query string (LRU Map or TanStack Query) while showing accessible aria-activedescendant keyboard navigation.
System Design Web Performance Q12. How do you optimize Core Web Vitals (LCP, INP, CLS) on an E-Commerce storefront?
For LCP (< 2.5s): SSR/edge-cache HTML, preload the hero image with fetchpriority="high", serve AVIF/WebP, and eliminate render-blocking JS. For INP (< 200ms): break long tasks (> 50ms) via code-splitting, virtualization, and useTransition. For CLS (< 0.1): reserve explicit width/height or aspect-ratio on all images, ad slots, and skeletons, and use font-display: swap.
System Design Auth Resilience Q13. How do you implement Single-Flight 401 Token Refresh when 5 parallel API calls fail simultaneously?
Maintain a single shared in-flight refreshPromise inside your Axios/fetch interceptor. When 5 parallel calls receive HTTP 401, only the first triggers POST /auth/refresh and stores the promise; the other 4 await that exact same refreshPromise and then transparently replay their original requests with the fresh token, clearing the promise in finally().
System Design Large Data Lists Q14. How do you render a 50,000-row financial table at 60 FPS without crashing browser memory?
Use DOM Windowing / Virtualization (e.g., TanStack Virtual) so only the ~25 visible rows plus a small overscan buffer exist in the DOM at any moment. Pair with server-side cursor pagination, memoized row cells, CSS contain: strict, and Web Workers if client-side sorting/filtering across 50k records is required.
System Design Frontend Security Q15. How do you defend a SPA against XSS, CSRF, and Supply-Chain script injection?
Never inject unsanitized HTML (sanitize with DOMPurify if unavoidable), store refresh tokens in HttpOnly + Secure + SameSite cookies instead of localStorage, enforce strict Content-Security-Policy (CSP) headers with nonces/allowlists, send anti-CSRF tokens on state-changing requests, and audit npm dependencies with lockfiles + Subresource Integrity (SRI).
Freshers JS Polyfills Q16. Write a production-safe Promise.all polyfill in JavaScript handling empty arrays and rejection ordering.
Promise.all must preserve input index order (not completion order!), wrap non-promise values via Promise.resolve(), resolve immediately with [] when passed an empty iterable, and reject immediately on the first rejection.
TypeScript Promise.all Polyfill (Preserves Result Order)typescript
export function promiseAll<T>(items: Iterable<T | Promise<T>>): Promise<T[]> {
return new Promise((resolve, reject) => {
const arr = Array.from(items);
if (arr.length === 0) return resolve([]);
const results = new Array<T>(arr.length);
let completed = 0;
arr.forEach((item, index) => {
Promise.resolve(item).then((value) => {
results[index] = value;
completed += 1;
if (completed === arr.length) resolve(results);
}, reject);
});
});
}
Freshers JS Polyfills Q17. Write a clean Debounce utility with cancel() support used in React/Angular search inputs.
Debounce resets a closure timer on every rapid invocation and exposes a cancel() method so component unmount hooks can prevent memory leaks or stale state updates.
Cancellable TypeScript Debounce Utilitytypescript
export function debounce<T extends (...args: any[]) => void>(fn: T, delayMs: number) {
let timer: ReturnType<typeof setTimeout> | null = null;
const debounced = (...args: Parameters<T>) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => fn(...args), delayMs);
};
debounced.cancel = () => { if (timer) clearTimeout(timer); };
return debounced;
}
Freshers React Hooks Q18. Why do stale closures happen inside useEffect or setInterval in React, and how do you fix them?
Every React render captures its own immutable snapshot of props and state. An interval created once inside useEffect(..., []) keeps reading the initial render’s count value forever. Fix by using functional state updates (setCount(c => c + 1)), including dependencies accurately, or storing mutable latest callbacks inside a useRef.
Experienced React 19 Actions Q19. Show how React 19 useActionState and useOptimistic simplify async form mutations without manual loading flags.
React 19 natively manages pending states, error boundaries, and automatic rollback during async form actions — cutting repetitive useState(isLoading/error) boilerplate while keeping UI updates instantaneous.
React 19 useOptimistic Comment Submissiontsx
function CommentList({ comments, onSave }: Props) {
const [optimistic, addOptimistic] = useOptimistic(
comments,
(state, newText: string) => [...state, { id: 'temp', text: newText, pending: true }]
);
async function submitAction(formData: FormData) {
const text = String(formData.get('text') ?? '');
addOptimistic(text);
await onSave(text); // Automatically rolls back optimistic state if this throws
}
return <form action={submitAction}>{/* ... */}</form>;
}
Experienced Angular 19 Signals Q20. Show how Angular 19 signal(), computed(), and @defer blocks cut bundle size and eliminate Zone.js checks.
computed() memoizes derived state lazily and only recalculates when read signals change. Pairing Signals with template @defer (on viewport) defers heavy chart or table chunks until the user scrolls near them.
Angular 19 Standalone Component with Signalstypescript
@Component({ standalone: true, selector: 'app-cart-summary', template: `Total: ₹{{ total() }}` })
export class CartSummaryComponent {
readonly items = signal([{ price: 1500, qty: 2 }]);
readonly total = computed(() =>
this.items().reduce((sum, item) => sum + item.price * item.qty, 0)
);
}
Experienced Next.js Caching Q21. How do Next.js App Router on-demand revalidation (revalidateTag / revalidatePath) and ISR work together?
Tag server fetch calls with next: { tags: ["products"] } so pages serve fast cached HTML at the edge, then invoke revalidateTag("products") from a webhook or Server Action immediately when an admin edits a record — giving near-static TTFB with instant freshness.
Experienced Auth Resilience Q22. Show the Single-Flight 401 Refresh Promise interceptor pattern in TypeScript.
Coalescing parallel 401 failures onto a single module-level refreshPromise guarantees only ONE /auth/refresh network call fires even if 6 dashboard widgets expire at the exact same millisecond.
Single-Flight 401 Refresh Token Queuetypescript
let refreshPromise: Promise<string> | null = null;
async function getFreshAccessToken(): Promise<string> {
if (!refreshPromise) {
refreshPromise = fetch('/api/auth/refresh', { method: 'POST', credentials: 'include' })
.then((res) => { if (!res.ok) throw new Error('Refresh failed'); return res.json(); })
.then((data) => data.accessToken)
.finally(() => { refreshPromise = null; });
}
return refreshPromise;
}
System Design Accessibility (a11y) Q23. How do you engineer an accessible production Modal Dialog (Focus Trap, ARIA & Escape handling)?
Use native <dialog> or role="dialog" aria-modal="true" with aria-labelledby, move initial focus inside the modal on open, trap Tab/Shift+Tab cycling within focusable children, close cleanly on Escape keydown, prevent background scroll, and restore focus back to the exact trigger button upon close.
System Design Real-Time UI Resilience Q24. How do you design WebSocket / SSE reconnection with exponential backoff and jitter in a live trading or dashboard UI?
Track reconnect attempt count, compute wait = min(maxDelay, baseDelay * 2^attempt) + randomJitter() to prevent thundering-herd reconnect storms when a server restarts, flush queued outbound events on reconnect, and request missed deltas using a monotonic lastEventId cursor.
System Design Micro-Frontends Q25. When should an enterprise adopt Micro-Frontends (Module Federation) vs a Monorepo (Turborepo/Nx)?
Default to a Monorepo (Nx/Turborepo) with shared UI packages whenever < 40 engineers work on one product — it avoids duplicated React/Angular runtimes, version skew, and cross-team CSS regressions. Adopt Module Federation only when large autonomous orgs truly require independent deployment cadences across distinct domains.