React Production Architecture Masterclass
Total Questions: 75 Curriculum: Core Mechanics & Fiber Internals (15), Logic & Hooks Engineering (15), Senior Production Scenarios (10), Principal Architecture & Systems (10)
Section 1: Core Fundamentals (Beginner / Medium)
Q1: How does React's Reconciliation and Virtual DOM Diffing algorithm work?
Level: Beginner
Technical Answer: React maintains an in-memory Virtual DOM tree. When state changes, React executes an O(n) heuristic diffing algorithm during the pure Render Phase: elements of different types tear down and mount new subtrees; elements of the same type reconcile props; list children use the unique 'key' prop to track identity and match items across reorders. Finally, the Commit Phase applies minimal batched mutations to the real browser DOM.
Code:
// Key prop identity prevents full subtree unmounting
export function TodoList({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
Workflow Diagram:
State Change ──> Render Phase (Diffing O(n)) ──> Fiber Reconciler ──> Commit Phase (DOM Mutation)
Behind the Question: Understanding Render vs Commit phases, key prop mechanics, and avoiding O(n^3) tree diffing.
Red Flags: Using array index as key when list order can change; thinking Virtual DOM always bypasses the browser DOM.
Q2: What causes unnecessary re-renders in React and how do useMemo and useCallback prevent them?
Level: Medium
Technical Answer: Components re-render when state changes, parents re-render, or subscribed contexts update. Non-primitive objects and functions create new references on every render ({} !== {}), breaking shallow equality checks (Object.is) in child components wrapped with React.memo(). useCallback caches function references, while useMemo caches computed values, preserving identity across renders.
Code:
const Child = React.memo(({ onAction, config }) => {
return <button onClick={onAction}>{config.label}</button>;
});
export function Parent() {
const [count, setCount] = useState(0);
const handleAction = useCallback(() => console.log('Action!'), []);
const config = useMemo(() => ({ label: 'Submit' }), []);
return <Child onAction={handleAction} config={config} />;
}
Workflow Diagram:
Parent Render ──> useCallback keeps 0x01 === 0x01 ──> React.memo(Child) Skips Render!
Behind the Question: Testing reference equality comprehension and avoiding premature or ineffective memoization.
Red Flags: Using useCallback without React.memo on child; omitting dependencies from the dependency array.
Q3: How does React's SyntheticEvent system work and why did React 17 move event delegation from document to root?
Level: Medium
Technical Answer: SyntheticEvent is a cross-browser wrapper around native DOM events conforming to the W3C spec. Prior to React 17, React attached all listeners to the 'document' node. In React 17+, event listeners are attached to the root DOM container (rootNode, e.g.
Code:
export function EventDemo() {
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
console.log('Synthetic event type:', e.type);
console.log('Native DOM event:', e.nativeEvent);
e.stopPropagation(); // Stops propagation in React's synthetic tree!
};
return <button onClick={handleClick}>Click Me</button>;
}
Workflow Diagram:
React 16: Events delegate to document (document.addEventListener)
React 17+: Events delegate to Root Container (<div id="root">.addEventListener) -> Safe Microfrontends!
Behind the Question: Understanding synthetic event pooling, microfrontend event containment, and native vs synthetic event bubbling.
Red Flags: Assuming e in React is the raw browser MouseEvent; thinking stopPropagation on native event stops synthetic event.
Q4: What are the exact execution timing differences between useEffect, useLayoutEffect, and useInsertionEffect?
Level: Medium
Technical Answer: useInsertionEffect executes synchronously before any DOM mutations are applied (designed strictly for CSS-in-JS libraries to inject
Code:
useInsertionEffect(() => {
// 1. Runs before DOM mutations (CSS-in-JS tag injection)
});
useLayoutEffect(() => {
// 2. Runs synchronously after DOM mutations, BEFORE browser paint (DOM measurement)
const rect = ref.current.getBoundingClientRect();
});
useEffect(() => {
// 3. Runs asynchronously AFTER browser paint (Data fetching, analytics)
});
Workflow Diagram:
Render Phase ──> useInsertionEffect ──> DOM Mutations ──> useLayoutEffect ──> Browser Paint ──> useEffect
Behind the Question: Evaluating knowledge of browser rendering pipeline, avoiding visual layout shifts, and selecting appropriate hooks.
Red Flags: Using useLayoutEffect for data fetching; not knowing that useLayoutEffect causes SSR warnings.
Q5: What is the difference between Controlled and Uncontrolled Components in React form handling?
Level: Beginner
Technical Answer: In Controlled Components, form input state is managed directly by React state (value={val} onChange={e => setVal(e.target.value)}), making React the single source of truth and enabling instant validation. In Uncontrolled Components, form state is managed by the browser DOM itself, accessed imperatively via useRef (or FormData on submit), which reduces re-render overhead in large enterprise forms.
Code:
// Controlled: React holds state on every keystroke
function ControlledInput() {
const [val, setVal] = useState('');
return <input value={val} onChange={e => setVal(e.target.value)} />;
}
// Uncontrolled: DOM holds state; read via ref on submit (0 re-renders!)
function UncontrolledInput() {
const inputRef = useRef<HTMLInputElement>(null);
const handleSubmit = (e) => {
e.preventDefault();
console.log('Value:', inputRef.current?.value);
};
return <form onSubmit={handleSubmit}><input ref={inputRef} /></form>;
}
Workflow Diagram:
Controlled: Keystroke ──> onChange ──> setState ──> Component Re-renders ──> Input Value Updated
Uncontrolled: Keystroke ──> Browser DOM updates directly (Zero React re-renders!)
Behind the Question: Assessing form architecture choices, performance trade-offs in heavy forms, and DOM vs React state.
Red Flags: Switching an input from uncontrolled to controlled dynamically (triggers React warning); storing 50 form inputs in single state without debouncing.
Q6: How does the React Context API propagate updates and what causes the Context Re-Render Thrashing bug?
Level: Medium
Technical Answer: When a Context Provider's value reference changes (Object.is), EVERY component subscribing to that context via useContext() unconditionally re-renders, bypassing React.memo() on intermediate components. Thrashing occurs when passing an inline object (value={{ user, theme }}) that creates a new reference on every render, causing all consumer components across the entire tree to re-render needlessly.
Code:
// Anti-pattern: Inline object causes every consumer to re-render!
// <AuthContext.Provider value={{ user, login, logout }}>
// Production Solution: Split contexts or memoize provider value
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = useCallback((u) => setUser(u), []);
const logout = useCallback(() => setUser(null), []);
const value = useMemo(() => ({ user, login, logout }), [user, login, logout]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
Workflow Diagram:
Provider Value Changes ──> All useContext() subscribers re-render (Bypasses React.memo!)
Fix: Memoize value + Split State Context from Dispatch Context.
Behind the Question: Evaluating context optimization patterns, context splitting, and avoiding global state bottlenecks.
Red Flags: Using Context as a drop-in replacement for high-frequency Redux/Zustand stores; putting state and actions in single un-memoized object.
Q7: How do React Error Boundaries catch errors, and what errors do they fail to intercept?
Level: Beginner
Technical Answer: Error Boundaries are class components implementing componentDidCatch(error, info) and/or static getDerivedStateFromError(error). They catch rendering errors, lifecycle hook errors, and errors inside constructors of their child component tree. Error Boundaries CANNOT catch: 1. Event handlers (e.g. onClick); 2. Asynchronous callbacks (setTimeout, fetch promises); 3. Server-Side Rendering errors; 4. Errors thrown inside the Error Boundary component itself.
Code:
export class GlobalErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Captured by boundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <div className="p-4 bg-red-100">Something crashed: {this.state.error?.message}</div>;
}
return this.props.children;
}
}
Workflow Diagram:
Child Component Render Throws ──> Caught by ErrorBoundary ──> getDerivedStateFromError ──> Renders Fallback UI
Behind the Question: Testing application resilience patterns, error isolation, and knowing boundary limitations.
Red Flags: Assuming try/catch works around JSX; expecting an Error Boundary to catch fetch promise errors in onClick.
Q8: What are React Portals (createPortal) and how does event bubbling behave through them?
Level: Medium
Technical Answer: ReactDOM.createPortal(children, domNode) renders children into a completely different DOM node outside the parent component's DOM hierarchy (e.g. document.body for modals, tooltips). Crucially, even though the portal node exists elsewhere in the real DOM tree, React's SyntheticEvent bubbling adheres to the React Virtual DOM hierarchy: a click inside a portal bubbles up to its React parent component, allowing event delegation across physical DOM boundaries.
Code:
import { createPortal } from 'react-dom';
export function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null;
return createPortal(
<div className="modal-backdrop" onClick={onClose}>
{/* Clicking inside modal stops bubbling so backdrop click doesn't close */}
<div className="modal-content" onClick={e => e.stopPropagation()}>
{children}
</div>
</div>,
document.body // Appended directly to body in real DOM!
);
}
Workflow Diagram:
Real DOM: document.body ──> [ Modal Container ]
React Tree: <App> ──> <ParentComponent> ──> <Modal> (Events bubble up through React Tree!)
Behind the Question: Assessing understanding of DOM rendering hierarchy vs React synthetic tree event propagation.
Red Flags: Believing portal events bubble up through the real DOM parent rather than the React tree.
Q9: How does useSyncExternalStore (React 18+) eliminate Tearing in Concurrent React?
Level: Medium
Technical Answer: In Concurrent React, rendering can pause and yield back to the browser. If a component reads from a mutable external store (Redux, Zustand, window.innerWidth) during an interruptible render, an external update could occur midway through rendering, causing different components in the same render cycle to read different values (known as 'Tearing'). useSyncExternalStore solves this by subscribing to external stores with synchronous consistency checks, forcing synchronous re-renders if the store mutates mid-render.
Code:
import { useSyncExternalStore } from 'react';
function subscribe(callback: () => void) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
export function useOnlineStatus() {
return useSyncExternalStore(
subscribe,
() => navigator.onLine, // Client snapshot
() => true // Server snapshot (SSR fallback)
);
}
Workflow Diagram:
Concurrent Render (Interruptible) ──> External Store Updates Mid-Render ──> Tearing Bug!
useSyncExternalStore ──> Detects store change ──> Restarts render with consistent snapshot!
Behind the Question: Testing deep understanding of React 18 concurrent rendering, external state management, and avoiding visual tearing.
Red Flags: Using useEffect with useState for external stores (causes extra renders and tearing in concurrent mode).
Q10: What does React.StrictMode do in development and why does it double-invoke renders and effects?
Level: Beginner
Technical Answer: StrictMode is a development-only tool that highlights potential problems in an application: it detects legacy string refs, deprecated findDOMNode usage, and unsafe lifecycle methods. Crucially, StrictMode intentionally double-invokes component render bodies and mount effects (mount -> unmount -> mount) in development. This stress-tests components to ensure that render bodies are pure and that useEffect cleanup functions properly tear down subscriptions, timers, and connections.
Code:
useEffect(() => {
const ws = new WebSocket('wss://stream.corp.internal');
// In StrictMode (dev), React mounts, unmounts, and re-mounts immediately.
// If cleanup is missing, multiple orphaned WebSocket connections leak!
return () => {
ws.close(); // Mandatory cleanup!
};
}, []);
Workflow Diagram:
StrictMode Lifecycle (Dev):
Render 1 ──> Render 2 (Checks for pure functions)
Mount Effect ──> Cleanup Effect ──> Mount Effect (Checks for missing cleanups)
Behind the Question: Evaluating whether candidate understands idempotency in effects and why side-effects must not live in render bodies.
Red Flags: Disabling StrictMode because 'it runs my API calls twice'; putting mutations inside top-level component render functions.
Q11: How does useTransition and startTransition optimize non-urgent state updates in React 18+?
Level: Medium
Technical Answer: Prior to React 18, all state updates were treated as urgent, blocking user input until the entire render finished. useTransition() allows developers to mark state updates as non-urgent transitions (e.g. filtering a 10,000-item table). Urgent updates (typing in an input) take priority, while the transition runs in the background without blocking the UI. If the user types a new character while the transition is computing, React interrupts and discards the outdated transition render.
Code:
import { useState, useTransition } from 'react';
export function SearchFilter() {
const [query, setQuery] = useState('');
const [filterResult, setFilterResult] = useState([]);
const [isPending, startTransition] = useTransition();
const handleChange = (e) => {
// 1. Urgent update: Updates input immediately at 60fps
setQuery(e.target.value);
// 2. Non-urgent update: Computes heavy filter in background without freezing input!
startTransition(() => {
setFilterResult(heavyFilter(e.target.value));
});
};
return (
<div>
<input value={query} onChange={handleChange} />
{isPending && <span>Rendering heavy list...</span>}
<List items={filterResult} />
</div>
);
}
Workflow Diagram:
User types 'A' ──> Urgent setQuery('A') (Fast paint)
──> startTransition(filter) (Background, interruptible)
User types 'B' ──> React INTERRUPTS filter('A')! ──> Computes filter('B') instead!
Behind the Question: Assessing knowledge of concurrent scheduling, responsive UI design, and avoiding main-thread input lag.
Red Flags: Using debouncing as the only solution for heavy rendering; wrapping urgent text input updates in startTransition.
Q12: What is useDeferredValue and how does it differ from traditional Debounce?
Level: Medium
Technical Answer: useDeferredValue accepts a value and returns a deferred copy of that value that 'lags behind' during heavy renders. Unlike traditional setTimeout debounce (which delays execution by an arbitrary fixed millisecond duration regardless of device speed), useDeferredValue is integrated into React's scheduler: on fast hardware, the update renders almost instantaneously; on slow mobile devices, it yields to user inputs, rendering as soon as the main thread is idle.
Code:
import { useState, useDeferredValue, useMemo } from 'react';
export function FastSearch() {
const [text, setText] = useState('');
const deferredText = useDeferredValue(text);
// Computes based on deferred value; input remains responsive
const list = useMemo(() => heavyQuery(deferredText), [deferredText]);
return (
<div>
<input value={text} onChange={e => setText(e.target.value)} />
<HeavyList items={list} />
</div>
);
}
Workflow Diagram:
Debounce: Fixed 300ms wait timer regardless of CPU capacity
useDeferredValue: Adaptive! Renders in 5ms on fast M3 Mac, yields on slow mobile CPU.
Behind the Question: Testing adaptive concurrency vs fixed-timer throttling.
Red Flags: Confusing useDeferredValue with debounced inputs; not memoizing the child component reading deferred value.
Q13: How does useId generate accessible, deterministic IDs across SSR and hydration?
Level: Beginner
Technical Answer: In SSR architectures, generating unique IDs using Math.random() or an in-memory counter produces different strings on the server and client, causing hydration mismatches. useId() generates a stable, unique base32-encoded string based on the component's position in the React Fiber tree. This guarantees identical IDs on both server and client without collisions or hydration errors.
Code:
import { useId } from 'react';
export function AccessibleFormField({ label }) {
const id = useId(); // Stable ID across SSR & Client hydration
return (
<div>
<label htmlFor={id}>{label}</label>
<input id={id} type="text" />
</div>
);
}
Workflow Diagram:
Server Render: useId() -> ':r1:' (HTML: <label for=":r1:">)
Client Hydration: useId() -> ':r1:' (Deterministic match -> 0 hydration mismatch!)
Behind the Question: Evaluating accessibility compliance, SSR determinism, and avoiding manual global ID counters.
Red Flags: Using useId() to generate keys in a dynamic .map() list (keys must come from data, not useId).
Q14: How do useImperativeHandle and forwardRef encapsulate and restrict imperative component APIs?
Level: Medium
Technical Answer: By default, passing a ref to a child component exposes the entire underlying HTML DOM node, violating encapsulation. forwardRef permits a parent to pass a ref down to a child. useImperativeHandle(ref, createHandle, [deps]) customizes the instance value exposed to the parent ref, exposing only specific allowed methods (e.g. .focus(), .reset()) while hiding raw DOM nodes and private internal state.
Code:
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
export interface VideoPlayerHandle {
play: () => void;
pause: () => void;
}
export const VideoPlayer = forwardRef<VideoPlayerHandle>((props, ref) => {
const videoRef = useRef<HTMLVideoElement>(null);
useImperativeHandle(ref, () => ({
play: () => videoRef.current?.play(),
pause: () => videoRef.current?.pause()
}));
return <video ref={videoRef} src="/video.mp4" />;
});
// Parent can ONLY call .play() and .pause(); cannot mutate video element styles directly!
Workflow Diagram:
Parent Component (Holds ref) ──> useImperativeHandle proxy { play(), pause() } ──> Child <video>
Behind the Question: Testing component boundary encapsulation, controlled imperative interfaces, and ref forwarding.
Red Flags: Exposing the entire raw DOM element when only one action is needed; using refs for data that belongs in state.
Q15: What are React 19 Actions and how does useActionState simplify asynchronous form submissions?
Level: Medium
Technical Answer: React 19 elevates asynchronous functions to 'Actions'. Actions automatically manage pending states, optimistic updates, and error handling. useActionState(actionFn, initialState) accepts an asynchronous action function, returning [state, formAction, isPending]. When invoked via form action={formAction}, React automatically manages loading states, resets inputs, and queues form submissions without manual useState loading flags.
Code:
// React 19 Action Paradigm
import { useActionState } from 'react';
async function updateUsernameAction(previousState: any, formData: FormData) {
const newName = formData.get('username') as string;
try {
await api.updateUser({ name: newName });
return { success: true, name: newName };
} catch (err: any) {
return { success: false, error: err.message };
}
}
export function ProfileForm() {
const [state, formAction, isPending] = useActionState(updateUsernameAction, null);
return (
<form action={formAction}>
<input name="username" required disabled={isPending} />
<button type="submit" disabled={isPending}>
{isPending ? 'Saving...' : 'Save Profile'}
</button>
{state?.error && <p className="text-red-500">{state.error}</p>}
</form>
);
}
Workflow Diagram:
Form Submit ──> actionFn() ──> isPending: true automatically ──> Action resolves ──> isPending: false
Behind the Question: Understanding modern React 19 asynchronous form management and deprecating legacy boilerplate.
Red Flags: Creating separate useState for isLoading, error, and data for every form submission.
Section 2: Logic & Hooks Engineering (Medium)
Q16: Predict console output and state updates with multiple consecutive setState calls.
Level: Medium
Technical Answer: In React 18, automatic batching bundles multiple state updates into a single re-render. Direct value calls setCount(count + 1) read from the same stale render closure, so three consecutive calls increment the count by only 1. Functional updates setCount(c => c + 1) receive the pending state from the queue, correctly incrementing by 3.
Code:
function Counter() {
const [count, setCount] = useState(0);
const handleDirect = () => {
setCount(count + 1); // 0 + 1
setCount(count + 1); // 0 + 1
setCount(count + 1); // 0 + 1 -> Final count: 1
};
const handleFunctional = () => {
setCount(c => c + 1); // 0 -> 1
setCount(c => c + 1); // 1 -> 2
setCount(c => c + 1); // 2 -> 3 -> Final count: 3
};
return <button onClick={handleFunctional}>Count: {count}</button>;
}
Workflow Diagram:
Direct: setCount(0+1) -> setCount(0+1) -> setCount(0+1) ──> Final State: 1
Functional: setCount(c=>c+1) -> (1)=>2 -> (2)=>3 ───────────────> Final State: 3
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q17: Predict the render behavior when mutating state objects directly without spreading.
Level: Medium
Technical Answer: React uses Object.is() shallow comparison to determine if state has changed. If an object is mutated directly (user.name = 'Bob') and passed to setUser(user), Object.is(user, user) evaluates to true; React bails out of rendering and the component does NOT update.
Code:
const [user, setUser] = useState({ name: 'Alice', age: 25 });
// Broken: Mutates existing object in-place
const brokenUpdate = () => {
user.name = 'Bob';
setUser(user); // Object.is(user, user) === true -> Bails out! No re-render!
};
// Correct: Creates new object reference
const correctUpdate = () => {
setUser(prev => ({ ...prev, name: 'Bob' })); // New reference -> Re-renders!
};
Workflow Diagram:
user.name = 'Bob'; setUser(user) ──> Object.is(0x01, 0x01) === true ──> BAILS OUT (No render)
setUser({ ...user }) ───────────> Object.is(0x01, 0x02) === false ──> Re-renders!
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q18: How do you detect and fix Stale Closures inside useEffect timer callbacks?
Level: Medium
Technical Answer: A stale closure occurs when an asynchronous callback captures state or props from an initial render and is not updated because dependencies are omitted from useEffect's dependency array. Using functional state updates (setCount(c => c + 1)) or useRef eliminates the stale closure without recreating the timer.
Code:
// Stale Closure Bug:
// useEffect(() => {
// const id = setInterval(() => setCount(count + 1), 1000); // Always sees count=0!
// return () => clearInterval(id);
// }, []); // Missing count dependency!
// Production Fix: Functional update accesses live pending state
export function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1); // Reads latest state without depending on outer count!
}, 1000);
return () => clearInterval(id);
}, []);
return <div>{count}</div>;
}
Workflow Diagram:
Render 0 (count=0) ──> setInterval closure captures count=0 indefinitely!
Functional updater: setCount(c => c + 1) reads directly from React's internal state cell.
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q19: How do you implement a custom useDebounce hook with automatic timer cleanup?
Level: Medium
Technical Answer: useDebounce accepts a value and delay, returning a debounced value. An internal useEffect sets up a setTimeout to update the debounced state, returning a cleanup function (clearTimeout) that cancels the timer if the input value changes before the delay expires.
Code:
import { useState, useEffect } from 'react';
export function useDebounce<T>(value: T, delay: number = 300): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Clears timer on keystroke: only latest value updates after delay
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
Workflow Diagram:
Input Stream: 'a' ──(timer set)── 'ap' ──(timer cleared & reset)── 'app' ──(300ms)──> Value: 'app'
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q20: How do you implement a custom usePrevious hook using useRef?
Level: Medium
Technical Answer: usePrevious stores the value of a prop or state from the previous render. A useRef container holds the value. A useEffect executes after the render commit phase to update ref.current with the current value, meaning during the current render, ref.current still holds the previous render's value.
Code:
import { useRef, useEffect } from 'react';
export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T>();
useEffect(() => {
ref.current = value; // Updated AFTER component render finishes
}, [value]);
return ref.current; // Returns previous render value during current render!
}
Workflow Diagram:
Render N: returns ref.current (Value N-1) ──> useEffect runs ──> updates ref.current = Value N
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q21: How do you implement a custom useOnClickOutside hook to dismiss dropdowns and modals?
Level: Medium
Technical Answer: The hook attaches a mousedown / touchstart listener to the document. In the callback, ref.current.contains(e.target) checks if the clicked DOM node is inside the target element. If not, the handler callback is invoked to close the element.
Code:
import { useEffect, RefObject } from 'react';
export function useOnClickOutside(ref: RefObject<HTMLElement>, handler: (event: Event) => void) {
useEffect(() => {
const listener = (event: Event) => {
// Do nothing if clicking ref's element or descendent elements
if (!ref.current || ref.current.contains(event.target as Node)) {
return;
}
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
};
}, [ref, handler]);
}
Workflow Diagram:
Click on Document ──> ref.current.contains(target) === false? YES ──> Invokes handler (Closes dropdown)
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q22: How do you implement a custom useIntersectionObserver hook for infinite scrolling?
Level: Medium
Technical Answer: The hook wraps the browser's native IntersectionObserver API. A callback ref or target ref is observed; when isIntersecting becomes true, an onIntersect callback is triggered to fetch the next page of paginated data.
Code:
import { useEffect, useRef } from 'react';
export function useInfiniteScroll(onIntersect: () => void, isEnabled: boolean) {
const sentinelRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!isEnabled || !sentinelRef.current) return;
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
onIntersect();
}
}, { threshold: 0.1 });
observer.observe(sentinelRef.current);
return () => observer.disconnect();
}, [onIntersect, isEnabled]);
return sentinelRef;
}
Workflow Diagram:
Scroll Down ──> Sentinel <div> enters viewport ──> isIntersecting: true ──> onIntersect() fetches next page
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q23: How do you implement a custom useLocalStorage hook with cross-tab event synchronization?
Level: Medium
Technical Answer: The hook reads initial state from localStorage on mount. When updated, it writes to localStorage and dispatches a custom window 'storage' event so all components and other open browser tabs synchronize their state in real time.
Code:
import { useState, useEffect } from 'react';
export function useLocalStorage<T>(key: string, initialValue: T): [T, (val: T) => void] {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});
const setValue = (value: T) => {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
window.dispatchEvent(new Event('local-storage'));
};
useEffect(() => {
const handleStorageChange = () => {
const item = window.localStorage.getItem(key);
if (item) setStoredValue(JSON.parse(item));
};
window.addEventListener('storage', handleStorageChange);
window.addEventListener('local-storage', handleStorageChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
window.removeEventListener('local-storage', handleStorageChange);
};
}, [key]);
return [storedValue, setValue];
}
Workflow Diagram:
setValue(theme) ──> localStorage.setItem ──> window.dispatchEvent('storage') ──> All tabs update!
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q24: How does React 18 Automatic Batching work across setTimeout, Promises, and Native Events?
Level: Medium
Technical Answer: In React 17, state updates inside setTimeout, Promise.then, or native event handlers were NOT batched, triggering multiple separate re-renders. In React 18, createRoot enables automatic batching universally: all state updates within a microtask or event tick are batched into a single render. Developers can opt out using flushSync() when synchronous DOM reads are required.
Code:
import { flushSync } from 'react-dom';
function BatchingDemo() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
const handleClick = () => {
setTimeout(() => {
// In React 18: Batched! Re-renders ONCE at the end of the callback
setCount(c => c + 1);
setFlag(f => !f);
}, 100);
};
const handleForcedImmediate = () => {
// Forces React to flush DOM mutation synchronously immediately
flushSync(() => setCount(c => c + 1));
// DOM is updated right here!
};
}
Workflow Diagram:
React 17: setTimeout ──> setCount (Render 1) ──> setFlag (Render 2) (Double Render!)
React 18: setTimeout ──> setCount + setFlag ──> Single Batched Render!
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q25: How do you implement the Context Splitting pattern to eliminate re-renders in consumers?
Level: Medium
Technical Answer: Components that read data re-render whenever the context value changes, even if they only need dispatch actions. Splitting context into two providers (StateContext for data, DispatchContext for stable callbacks) ensures action-only components never re-render when state updates.
Code:
const CounterStateContext = React.createContext<number>(0);
const CounterDispatchContext = React.createContext<React.Dispatch<any>>(() => {});
export function CounterProvider({ children }) {
const [state, dispatch] = useReducer((s, a) => s + 1, 0);
return (
<CounterStateContext.Provider value={state}>
<CounterDispatchContext.Provider value={dispatch}>
{children}
</CounterDispatchContext.Provider>
</CounterStateContext.Provider>
);
}
// Button only subscribes to DispatchContext -> NEVER re-renders when count changes!
export function IncrementBtn() {
const dispatch = useContext(CounterDispatchContext);
return <button onClick={() => dispatch()}>+1</button>;
}
Workflow Diagram:
StateContext (value=count) ──> Subscribed Displays Re-render
DispatchContext (value=dispatch) ──> Action Buttons SKIP Render!
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q26: How do you implement Virtual Scrolling (Windowing) for a 100,000-row table in React?
Level: Medium
Technical Answer: Rendering 100,000 DOM nodes crashes browser layout engines. Virtual scrolling renders only the visible slice of items (e.g. 20 rows) plus a buffer, using top and bottom spacer padding or absolute transform positioning based on scrollTop.
Code:
import React, { useState } from 'react';
const ROW_HEIGHT = 40;
const VISIBLE_COUNT = 15;
export function VirtualList({ items }: { items: string[] }) {
const [scrollTop, setScrollTop] = useState(0);
const startIndex = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - 2);
const endIndex = Math.min(items.length, startIndex + VISIBLE_COUNT + 4);
const visibleItems = items.slice(startIndex, endIndex);
return (
<div
style={{ height: VISIBLE_COUNT * ROW_HEIGHT, overflowY: 'auto' }}
onScroll={e => setScrollTop(e.currentTarget.scrollTop)}
>
<div style={{ height: items.length * ROW_HEIGHT, position: 'relative' }}>
<div style={{ transform: `translateY(${startIndex * ROW_HEIGHT}px)` }}>
{visibleItems.map((item, idx) => (
<div key={startIndex + idx} style={{ height: ROW_HEIGHT }}>
{item}
</div>
))}
</div>
</div>
</div>
);
}
Workflow Diagram:
Total 100,000 rows (4,000,000px height)
[ Viewport: 15 visible rows rendered ] ──(Translate Y)──> 99.98% DOM nodes omitted!
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q27: How do you implement the Compound Components pattern in React?
Level: Medium
Technical Answer:
Compound components share implicit state via Context without explicit prop drilling, allowing consumers to arrange flexible sub-components (e.g.
Code:
const TabContext = React.createContext<{ active: string; setActive: (id: string) => void } | null>(null);
export function Tabs({ defaultTab, children }: { defaultTab: string; children: React.ReactNode }) {
const [active, setActive] = useState(defaultTab);
return <TabContext.Provider value={{ active, setActive }}>{children}</TabContext.Provider>;
}
Tabs.Tab = function Tab({ id, children }: { id: string; children: React.ReactNode }) {
const ctx = useContext(TabContext)!;
return (
<button
className={ctx.active === id ? 'active font-bold' : ''}
onClick={() => ctx.setActive(id)}
>
{children}
</button>
);
};
Tabs.Panel = function Panel({ id, children }: { id: string; children: React.ReactNode }) {
const ctx = useContext(TabContext)!;
return ctx.active === id ? <div>{children}</div> : null;
};
Workflow Diagram:
<Tabs> (Holds active tab state)
├── <Tabs.Tab id="1"> (Consumes context to switch)
└── <Tabs.Panel id="1"> (Conditionally renders content)
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q28: What are React Server Components (RSC) vs Client Components in React 19 / Next.js?
Level: Medium
Technical Answer: Server Components run exclusively on the server and stream serialized Virtual DOM data to the client with zero client bundle impact. Client Components ('use client') pre-render HTML on the server and hydrate in the browser, providing interactivity, event listeners, and hooks.
Code:
// Server Component (Default, zero client JS bundle)
import db from '@/lib/db';
import { ClientCounter } from './ClientCounter';
export default async function ProductPage({ id }) {
const product = await db.products.findById(id); // Server DB call
return (
<div>
<h1>{product.title}</h1>
<ClientCounter initialStock={product.stock} />
</div>
);
}
Workflow Diagram:
Server Component ──(RSC Payload + HTML)──> Zero Client JS Bundle!
Client Component ──('use client')─────────> Hydrates with event listeners in browser
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q29: How do you test React components effectively using React Testing Library?
Level: Medium
Technical Answer: React Testing Library emphasizes testing components as end users interact with them rather than testing internal implementation details. Queries prioritize accessibility roles (getByRole, findByText) and fire user events asynchronously via @testing-library/user-event.
Code:
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Counter } from './Counter';
test('increments counter on button click', async () => {
const user = userEvent.setup();
render(<Counter />);
const button = screen.getByRole('button', { name: /increment/i });
expect(screen.getByText(/count: 0/i)).toBeInTheDocument();
await user.click(button);
expect(screen.getByText(/count: 1/i)).toBeInTheDocument();
});
Workflow Diagram:
Render Component ──> Query by accessible role (getByRole) ──> userEvent.click() ──> Assert visible output
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Q30: How does React.memo custom comparison function (arePropsEqual) work?
Level: Medium
Technical Answer: By default, React.memo performs a shallow equality check (Object.is) on each prop. A custom comparison function arePropsEqual(prevProps, nextProps) can be passed: if it returns TRUE, React skips rendering; if it returns FALSE, React re-renders the component.
Code:
interface DataProps {
id: string;
payload: { score: number; ignoredMetadata: string };
}
const HeavyCard = React.memo(
function HeavyCard({ id, payload }: DataProps) {
return <div>User {id}: Score {payload.score}</div>;
},
// Custom comparison: Only re-render if 'score' or 'id' changes!
(prev, next) => prev.id === next.id && prev.payload.score === next.payload.score
);
Workflow Diagram:
prevProps vs nextProps ──> arePropsEqual() returns true ──> Skips Render!
──> arePropsEqual() returns false ──> Re-renders!
Behind the Question: Evaluating React hooks mechanics, state batching, and performance patterns.
Red Flags: Relying on inline functions without understanding reference equality; mutating state directly.
Section 3: Senior Production Scenarios (Senior)
Q31: SSR / RSC Hydration Mismatch & Cascading Layout Shifts in Next.js / React 19
Level: Senior
Scenario: A Next.js 14 dashboard reports console errors: 'Text content does not match server-rendered HTML' followed by a visual layout flash and 500ms unresponsive buttons on load.
Impact: Degraded Core Web Vitals (CLS > 0.3, INP penalties), failed button clicks on load, and SEO rank loss.
Root Cause: The server render evaluated non-deterministic client-only values (new Date().toLocaleTimeString() or localStorage) directly in component body before hydration.
Fix: Isolate browser data into useEffect or useSyncExternalStore; render identical skeleton fallback during SSR pass.
Code:
export function LocalizedTime() {
const [time, setTime] = useState<string | null>(null);
useEffect(() => {
// Executes ONLY in client browser after hydration completes
setTime(new Date().toLocaleTimeString());
}, []);
if (!time) return <span className="skeleton">Loading time...</span>;
return <span>{time}</span>;
}
Workflow Diagram:
Server Render: <span>Loading time...</span>
Client Initial: <span>Loading time...</span> (Match! 0 Hydration Mismatch)
Client Mount: setTime(...) -> Updates cleanly without layout shift!
Interviewer Notes: Testing SSR lifecycle mastery, deterministic hydration, and avoiding layout shifts.
Red Flags: Using suppressHydrationWarning everywhere; disabling SSR completely.
Q32: Stale Closures and Out-of-Order Asynchronous Search Results in Fast Autocomplete
Level: Senior
Scenario: Users typing quickly in a search bar see results for 'app' overwrite results for 'applesauce' due to network jitter, returning irrelevant data.
Impact: Customers purchase incorrect products or trade on stale data; direct revenue loss.
Root Cause: Un-aborted earlier fetch promises resolved after later fetch promises, writing stale state over fresh state.
Fix: Use AbortController inside useEffect cleanup to abort in-flight requests when query updates.
Code:
useEffect(() => {
if (!query) return;
const ac = new AbortController();
fetch(`/api/search?q=${query}`, { signal: ac.signal })
.then(r => r.json())
.then(data => setResults(data))
.catch(err => { if (err.name !== 'AbortError') setError(err); });
// Cleanup: Instantly cancels pending network request when user types next key!
return () => ac.abort();
}, [query]);
Workflow Diagram:
Type 'app' ──> Request 1 sent
Type 'apple' ──> Request 1 ABORTED! ──> Request 2 sent ──> Only Request 2 displayed!
Interviewer Notes: Assessing client-side race condition mitigation and AbortController integration.
Red Flags: Assuming promises resolve in arrival order; leaving dangling async callbacks.
Q33: Memory Leak from Un-Subscribed WebSocket Listeners in Frequently Toggled Modals
Level: Senior
Scenario: A trading terminal component connecting to a live order book leaks memory. Every time the modal opens and closes, memory increases by 50MB until the browser tab crashes.
Impact: Browser tab crashes during critical market trading sessions.
Root Cause: The useEffect hook opened a WebSocket subscription but lacked a return cleanup function, leaving orphaned connection listeners accumulating in heap.
Fix: Return a cleanup function from useEffect that closes sockets or calls unsubscribe.
Code:
useEffect(() => {
const socket = new WebSocket('wss://stream.market.corp/orders');
socket.onmessage = (e) => setOrders(JSON.parse(e.data));
// Mandatory teardown contract
return () => {
socket.close();
};
}, []);
Workflow Diagram:
Modal Open ──> Socket Connected
Modal Close ──> useEffect cleanup closes socket (Zero memory leak!)
Interviewer Notes: Verifying memory leak prevention and effect lifecycle contracts.
Red Flags: Relying on garbage collection to close network sockets; omitting cleanup functions.
Q34: Context Provider Re-Render Storm Freezing Mega-Menu Navigation
Level: Senior
Scenario: In a large enterprise app, updating a cart counter inside a global AppContext causes the entire page (including thousands of navigation items) to re-render, dropping FPS to 15.
Impact: Janky user experience, failed responsiveness audits, high INP.
Root Cause: A single monolithic Context Provider held both cart state and navigation state, passing an un-memoized object value.
Fix: Split monolithic context into focused, domain-specific contexts and wrap values in useMemo.
Code:
// Domain-specific Cart Context (Isolated from Navigation)
export function CartProvider({ children }) {
const [items, setItems] = useState([]);
const value = useMemo(() => ({ items, setItems }), [items]);
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}
Workflow Diagram:
Monolithic Context: Cart updates ──> Entire App (Nav, Table, Modals) Re-renders!
Split Context: Cart updates ──> ONLY <CartBadge> Re-renders!
Interviewer Notes: Testing enterprise state architecture and avoiding Context re-render cascades.
Red Flags: Using React Context for all global state in high-frequency applications.
Q35: Virtual Table DOM Thrashing under High-Frequency WebSocket Updates
Level: Senior
Scenario: A 10,000-row virtualized data grid receiving 500 WebSocket tick updates per second suffers from micro-stutters and browser freeze.
Impact: Traders cannot interact with charts or inputs during market volatility.
Root Cause: Each WebSocket message triggered a component-level setState, causing React's reconciler to run 500 times per second.
Fix: Throttle state updates to 60fps using requestAnimationFrame or update DOM cells imperatively via refs for ultra-hot values.
Code:
class TickerBatcher {
private queue = [];
private rafId = null;
push(tick, setTicks) {
this.queue.push(tick);
if (!this.rafId) {
this.rafId = requestAnimationFrame(() => {
setTicks(prev => mergeTicks(prev, this.queue));
this.queue = [];
this.rafId = null;
});
}
}
}
Workflow Diagram:
500 msgs/sec ──> RAF Batcher (60Hz Cap) ──> Max 60 renders/sec (Butter-smooth UI!)
Interviewer Notes: Assessing knowledge of high-frequency data streaming and rendering synchronization with display refresh rate.
Red Flags: Calling setState directly on every incoming WebSocket packet.
Q36: Formik / React Hook Form State Lag under 500+ Dynamic Form Fields
Level: Senior
Scenario: A complex insurance underwriting form with 500 inputs experiences 300ms typing latency per keystroke when controlled state re-renders the entire form.
Impact: Severe typing lag, user frustration, input drop.
Root Cause: The entire form was bound to a single top-level controlled state object; every keystroke re-rendered 500 child input components.
Fix: Migrate to uncontrolled form inputs using React Hook Form (register) or decouple fields using isolated controller components.
Code:
import { useForm } from 'react-hook-form';
export function MassiveInsuranceForm() {
// Uncontrolled inputs: keystrokes do NOT re-render the parent form!
const { register, handleSubmit } = useForm();
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
{fields.map(f => (
<input key={f.name} {...register(f.name)} />
))}
<button type="submit">Submit</button>
</form>
);
}
Workflow Diagram:
Controlled Form: Keystroke ──> Top-Level setState ──> 500 Inputs Re-render (300ms lag)
Uncontrolled (RHF): Keystroke ──> Local DOM updates ──> 0 Input Re-renders (0ms lag!)
Interviewer Notes: Testing form performance engineering and understanding controlled vs uncontrolled scaling.
Red Flags: Debouncing controlled inputs as a workaround instead of adopting uncontrolled architectures.
Q37: Uncaught Asynchronous Promise Rejections Crashing React Suspense Boundaries
Level: Senior
Scenario: A component wrapped in React Suspense throws an unhandled rejection when an API endpoint returns 500, unmounting the entire application instead of showing the fallback.
Impact: Total white screen of death across production routes.
Root Cause: Suspense only catches promises that are thrown during rendering; uncaught rejected promises inside un-awaited async handlers bypass Suspense and crash the app.
Fix: Combine React Suspense with an ErrorBoundary wrapping the component tree.
Code:
<ErrorBoundary fallback={<ErrorCard message="Failed to load user profile" />}>
<Suspense fallback={<ProfileSkeleton />}>
<UserProfile userId="101" />
</Suspense>
</ErrorBoundary>
Workflow Diagram:
Promise Pending ──> Suspense displays <ProfileSkeleton />
Promise Rejects ──> ErrorBoundary catches rejection ──> Displays <ErrorCard />
Interviewer Notes: Evaluating proper composition of Suspense and Error Boundaries.
Red Flags: Assuming Suspense handles runtime errors (Suspense only handles pending loading states).
Q38: Third-Party Script DOM Mutations Triggering Invariant Violation in React
Level: Senior
Scenario: A third-party translation or accessibility widget (Google Translate) mutates text nodes directly inside a React component, causing React to crash with 'Failed to execute removeChild on Node'.
Impact: Application crashes for international users using browser translation extensions.
Root Cause: React reconciler expects the real DOM to match its internal Fiber tree. Direct external DOM mutations break Fiber node pointers.
Fix: Wrap third-party widgets in a dedicated container with suppressHydrationWarning and isolate them inside shadow DOM or uncontrolled ref containers.
Code:
export function SafeThirdPartyWrapper({ htmlContent }) {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
// External scripts manipulate DOM ONLY inside this isolated ref container
if (containerRef.current) {
containerRef.current.innerHTML = htmlContent;
}
}, [htmlContent]);
// React renders empty shell and never diffs inner contents
return <div ref={containerRef} />;
}
Workflow Diagram:
React Managed Tree ──> Isolated <div ref> ──> Third-Party Script Mutates Inner DOM (React ignores inner changes!)
Interviewer Notes: Testing integration between React virtual DOM and external imperative DOM scripts.
Red Flags: Letting third-party scripts modify arbitrary React-rendered text nodes directly.
Q39: CSS-in-JS Runtime Injection Performance Penalties during Rapid Animation
Level: Senior
Scenario: An animated dashboard using runtime CSS-in-JS (styled-components / Emotion) drops frames during drag-and-drop interactions. DevTools shows 40% of scripting time spent in insertRule.
Impact: Janky animations, sluggish drag operations, high CPU usage on client.
Root Cause: Generating dynamic CSS strings on every frame causes the CSS-in-JS library to generate new class names, recalculate hashes, and execute CSSStyleSheet.insertRule() on every render.
Fix: Use CSS variables for dynamic values (style={{ '--x': ${pos.x}px }}) or migrate to zero-runtime CSS (Tailwind, Vanilla Extract).
Code:
// Anti-pattern: Generates 60 unique CSS rules per second!
// const Box = styled.div`transform: translate(${props => props.x}px);`;
// Production Solution: CSS Variables with static utility classes
export function DraggableBox({ x, y }) {
return (
<div
className="absolute transition-none"
style={{ transform: `translate3d(${x}px, ${y}px, 0)` }}
/>
);
}
Workflow Diagram:
Runtime CSS-in-JS: Drag ──> Generate class hash ──> insertRule() ──> Style Recalculation (15fps)
Inline Transform / CSS Vars: Drag ──> Direct GPU Composite ──> 60fps Butter Smooth!
Interviewer Notes: Assessing CSS architecture performance, CSS-in-JS runtime costs, and GPU compositing.
Red Flags: Using styled-components dynamic interpolations for 60fps animations.
Q40: Microfrontend Multiple React Instances Clashing on Shared Host Pages
Level: Senior
Scenario: A microfrontend architecture loads two independent sub-apps on the same page. Suddenly, React hooks fail with 'Invalid hook call: Hooks can only be called inside the body of a function component'.
Impact: Complete microfrontend loading failure in production.
Root Cause: Both microfrontends bundled their own copy of the 'react' package; calling a hook created by React Instance A inside a component rendered by React Instance B breaks hook dispatcher state.
Fix: Configure Webpack Module Federation or import maps to treat 'react' and 'react-dom' as strict shared singletons.
Code:
// Module Federation Config
shared: {
react: { singleton: true, requiredVersion: '^18.2.0', strictVersion: true },
'react-dom': { singleton: true, requiredVersion: '^18.2.0', strictVersion: true }
}
Workflow Diagram:
Microfrontend 1 (React A) ──┐
├── Singleton Negotiation ──> Single React Instance on window
Microfrontend 2 (React B) ──┘
Interviewer Notes: Testing microfrontend integration pitfalls and shared library singleton management.
Red Flags: Bundling React inside every microfrontend bundle independently.
Section 4: Principal Architecture & Systems (Principal)
Q41: Architecting Enterprise State Management: Zustand vs Redux Toolkit vs Signals
Level: Principal
Scenario: An enterprise SaaS platform evaluates state management architectures. Redux boilerplate is slowing feature delivery, while Context API causes re-render cascades.
Impact: High development friction, bloated bundle size, and rendering bottlenecks.
Root Cause: Mismatched state abstraction: using Context for high-frequency stores, or using heavyweight Redux for simple transient UI state.
Fix: Adopt Zustand for lightweight atomic selector-based stores, TanStack Query for server state cache, and Signals/Jotai for granular atomic re-renders.
Code:
import { create } from 'zustand';
interface UserStore {
user: User | null;
setUser: (u: User) => void;
}
export const useUserStore = create<UserStore>((set) => ({
user: null,
setUser: (user) => set({ user })
}));
// Component only re-renders when 'user.name' changes (Selective Subscription!)
export function UserName() {
const userName = useUserStore(s => s.user?.name);
return <span>{userName}</span>;
}
Workflow Diagram:
Zustand Store ──(Selector: s.user.name)──> ONLY subscribers to that property re-render!
(No Context Providers, Zero re-render cascades!)
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Q42: Server-Driven UI (SDUI) Architecture with Dynamic React Component Registries
Level: Principal
Scenario: A mobile web app needs to change checkout and dashboard layouts dynamically based on user segments without waiting for multi-day web build and deployment cycles.
Impact: Slow iteration speed for marketing experiments and segment promotions.
Root Cause: Hardcoded JSX layout hierarchies requiring code changes and builds for every UI adjustment.
Fix: Implement Server-Driven UI (SDUI): server responds with JSON layout schemas referencing registered component schemas, rendered dynamically via an extensible Component Registry.
Code:
const COMPONENT_REGISTRY: Record<string, React.FC<any>> = {
Banner: ({ title, cta }) => <div className="banner">{title} <button>{cta}</button></div>,
Carousel: ({ items }) => <div className="carousel">{items.map(renderItem)}</div>
};
export function DynamicScreenRenderer({ schema }) {
return (
<div className="sdui-screen">
{schema.components.map(comp => {
const Component = COMPONENT_REGISTRY[comp.type];
return Component ? <Component key={comp.id} {...comp.props} /> : null;
})}
</div>
);
}
Workflow Diagram:
Server JSON API Schema ──> DynamicScreenRenderer ──> Component Registry ──> Native React Elements
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Q43: Offloading Heavy Client Computations to Web Workers via React Custom Hooks
Level: Principal
Scenario: A crypto-wallet web application executing client-side zero-knowledge proof generation freezes the entire UI for 8 seconds, failing user touch interactions.
Impact: Unusable UI, mobile browser kill warnings, poor user ratings.
Root Cause: Computationally intensive mathematical operations ran synchronously on the single browser main thread.
Fix: Offload proof generation to a dedicated Web Worker via Comlink and expose a clean React hook interface with loading and progress states.
Code:
import { useState, useEffect } from 'react';
export function useZKProofWorker() {
const [worker, setWorker] = useState<Worker | null>(null);
useEffect(() => {
const w = new Worker(new URL('./proofWorker.ts', import.meta.url), { type: 'module' });
setWorker(w);
return () => w.terminate();
}, []);
const generateProof = (payload: any): Promise<string> => {
return new Promise((resolve, reject) => {
if (!worker) return reject('Worker not ready');
worker.onmessage = (e) => resolve(e.data.proof);
worker.onerror = reject;
worker.postMessage(payload);
});
};
return { generateProof };
}
Workflow Diagram:
Main Thread (UI 60fps) ──postMessage(payload)──> Web Worker (8s ZK-Proof calculation)
◄──onmessage(proof)─────────/
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Q44: Designing Accessible Headless Design Systems with Radix UI / React Aria
Level: Principal
Scenario: An enterprise company fails an ADA compliance accessibility audit (WCAG 2.1 AA) due to custom dropdowns and dialogs lacking ARIA roles, focus traps, and keyboard navigation.
Impact: Legal compliance lawsuit risks and inaccessibility for assistive technology users.
Root Cause: Building complex accessible interactive widgets from raw
Fix: Adopt headless component primitives (Radix UI, React Aria) that encapsulate 100% of WAI-ARIA behavior, focus traps, and keyboard accessibility, applying custom styling via Tailwind.
Code:
import * as Dialog from '@radix-ui/react-dialog';
export function AccessibleModal({ triggerText, title, children }) {
return (
<Dialog.Root>
<Dialog.Trigger asChild>
<button>{triggerText}</button>
</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Overlay className="backdrop-blur" />
<Dialog.Content className="dialog-window">
<Dialog.Title>{title}</Dialog.Title>
{children}
<Dialog.Close asChild>
<button aria-label="Close dialog">X</button>
</Dialog.Close>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
);
}
Workflow Diagram:
Radix Primitive (Focus Trap, Esc to Close, ARIA Attributes) + Custom Design System Tailwind Styling = 100% Accessible
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Q45: Real-Time Collaborative Canvas / Document State with React and CRDTs
Level: Principal
Scenario: A collaborative whiteboarding tool in React experiences desynchronized shapes and flicker when multiple remote users move objects simultaneously.
Impact: Corrupted collaborative sessions, customer design rework.
Root Cause: Using naive WebSocket broadcast state overwrites; remote updates triggered full React canvas re-renders.
Fix: Integrate Yjs CRDT shared types, updating local canvas elements via direct imperative transforms without full React reconciliation cycles.
Code:
import * as Y from 'yjs';
import { useSyncExternalStore } from 'react';
const ydoc = new Y.Doc();
const yshapes = ydoc.getMap('shapes');
export function useCollaborativeShapes() {
return useSyncExternalStore(
(callback) => {
yshapes.observe(callback);
return () => yshapes.unobserve(callback);
},
() => yshapes.toJSON()
);
}
Workflow Diagram:
Remote Users ──WebSocket──> Yjs Doc (CRDT) ──> yshapes.observe ──> useSyncExternalStore ──> Smooth Update
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Q46: Optimistic UI Updates with Automated Rollbacks on API Mutation Failures
Level: Principal
Scenario: A social network reaction button has a 300ms network delay. When users click 'Like', the UI waits 300ms before incrementing the count, feeling sluggish.
Impact: Sluggish user experience, reduced user engagement metrics.
Root Cause: Waiting for server mutation confirmation before updating client UI.
Fix: Implement Optimistic UI updates with TanStack Query or React 19 useOptimistic, immediately rendering the expected state and rolling back on network failure.
Code:
import { useOptimistic } from 'react';
export function LikeButton({ currentLikes, onLikeAction }) {
const [optimisticLikes, setOptimisticLikes] = useOptimistic(
currentLikes,
(state, delta: number) => state + delta
);
const handleClick = async () => {
// 1. Instantly increment in UI (0ms perceived latency!)
setOptimisticLikes(1);
try {
await onLikeAction();
} catch {
// Automatically rolls back if onLikeAction throws!
}
};
return <button onClick={handleClick}>Likes: {optimisticLikes}</button>;
}
Workflow Diagram:
User Clicks ──> useOptimistic renders (count + 1) immediately (0ms!)
Server Mutation Fails ──> Automatically rolls back to previous state!
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Q47: Micro-Frontend Shell Architecture with React Module Federation and Isolation
Level: Principal
Scenario: An enterprise portal integrates 8 autonomous microfrontend teams. A bug in the Checkout microfrontend throws an uncaught error that unmounts the entire portal application shell.
Impact: Single microfrontend crash causes company-wide platform outage.
Root Cause: Lack of failure domain isolation across microfrontend boundaries.
Fix: Wrap every federated microfrontend in an independent Error Boundary, Suspense fallback, and CSS isolation container.
Code:
export function SafeRemoteMicrofrontend({ remoteComponent: RemoteComponent, name }) {
return (
<ErrorBoundary fallback={<div className="mfe-error">Failed to load {name} widget</div>}>
<Suspense fallback={<div className="mfe-skeleton">Loading {name}...</div>}>
<RemoteComponent />
</Suspense>
</ErrorBoundary>
);
}
Workflow Diagram:
MFE Shell ──> [ ErrorBoundary + Suspense ] ──> MFE Checkout (Throws Error)
Result: ONLY Checkout shows fallback; Header, Nav, and Cart remain 100% operational!
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Q48: Automated Performance Gating in CI: Render Time Profiling with React Profiler API
Level: Principal
Scenario: A team merges a code change that accidentally introduces a 400ms render regression in the primary checkout funnel, which is only noticed after a conversion drop in production.
Impact: Conversion rate dropped by 8%, direct revenue impact.
Root Cause: No automated CI/CD performance gating for component render durations.
Fix: Instrument React's Profiler API in automated E2E tests (Playwright) to record actualDuration and assert that p95 render times remain below budget.
Code:
import { Profiler } from 'react';
function onRenderCallback(id, phase, actualDuration, baseDuration) {
if (actualDuration > 16) {
console.warn(`[PERF VIOLATION] ${id} took ${actualDuration.toFixed(2)}ms to render!`);
}
}
export function ProfiledCheckout() {
return (
<Profiler id="CheckoutFunnel" onRender={onRenderCallback}>
<CheckoutForm />
</Profiler>
);
}
Workflow Diagram:
CI Pipeline E2E Test ──> React Profiler records actualDuration > 16ms ──> PR Check Fails (Blocks merge!)
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Q49: Fleet-Wide INP (Interaction to Next Paint) Optimization: Concurrency, Transitions, and Yielding
Level: Principal
Scenario: Google Search Console flags an enterprise e-commerce site with poor INP (> 500ms). Mobile users clicking filter checkboxes experience a noticeable lag before the checkbox toggles visually.
Impact: SEO ranking drops by 15%, Core Web Vitals failure.
Root Cause: The click handler executed heavy filtering and state updates synchronously inside the same task, delaying the visual paint of the checkbox toggle.
Fix: Separate the visual toggle (urgent state) from the data filtering (non-urgent transition via startTransition) to guarantee next paint in under 50ms.
Code:
export function FastFilterCheckbox({ label, onFilterChange }) {
const [checked, setChecked] = useState(false);
const [, startTransition] = useTransition();
const handleToggle = () => {
// 1. Urgent: Toggles checkbox visual state instantly (<16ms paint!)
setChecked(c => !c);
// 2. Non-urgent: Runs heavy filtering in background without delaying paint
startTransition(() => {
onFilterChange(!checked);
});
};
return <input type="checkbox" checked={checked} onChange={handleToggle} />;
}
Workflow Diagram:
Click ──> setChecked() paints visually in 8ms (INP < 50ms!)
──> startTransition(filter) runs in background (Zero UI lag!)
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Q50: Progressive Web App (PWA) Offline Synchronization and Optimistic Mutation Rollbacks
Level: Principal
Scenario: A field technician application needs to record inspection reports while offline in remote areas without cellular connection, synchronizing automatically when back online.
Impact: Field agents lose inspection data, manual paper reporting fallback required.
Root Cause: Application assumed continuous network connectivity and dropped mutations when offline.
Fix: Architect an offline mutation queue backed by IndexedDB. When online, a background sync service replays mutations sequentially with exponential backoff and conflict resolution.
Code:
import { get, set } from 'idb-keyval';
export async function queueOfflineMutation(mutation) {
const queue = (await get('offline_mutation_queue')) || [];
queue.push({ ...mutation, id: crypto.randomUUID(), timestamp: Date.now() });
await set('offline_mutation_queue', queue);
}
window.addEventListener('online', async () => {
const queue = (await get('offline_mutation_queue')) || [];
for (const item of queue) {
try {
await api.replay(item);
} catch (err) {
console.error('Replay failed, retrying later:', err);
break;
}
}
await set('offline_mutation_queue', []);
});
Workflow Diagram:
Offline: Action ──> Queued in IndexedDB (0 data lost)
Online: 'online' event fires ──> Background queue drain ──> Server sync complete!
Interviewer Notes: Testing systems architecture, state management at scale, and executive engineering governance.
Red Flags: Suggesting client-side performance issues can be solved by upgrading server hardware; ignoring mobile device CPU constraints.
Section 5: Advanced Senior & Principal Architecture (Q51–Q75)
Q51: Stale Closures in useEffect and useCallback Under Asynchronous Timers
Level: Senior / Principal
Scenario: A dashboard metrics widget uses setInterval inside useEffect to poll a counter every 1 second. The displayed counter value never increments beyond 1, even after 10 seconds.
Impact: Stale UI display and incorrect calculation state across user sessions.
Root Cause:
The effect closure captured the initial state value (count = 0) at mount time because the dependency array was empty []. Every subsequent interval tick executes the closure with the captured initial value 0 + 1 = 1.
Fix:
Use functional state updates (setCount(prev => prev + 1)) or use a ref (useRef) to store mutable state without triggering closure staleness.
Code:
import { useEffect, useState, useRef } from 'react';
export function MetricsWidget() {
const [count, setCount] = useState(0);
// BUGGY: Captures count = 0 forever!
// useEffect(() => {
// const id = setInterval(() => setCount(count + 1), 1000);
// return () => clearInterval(id);
// }, []);
// FIXED: Functional state update eliminates closure dependency
useEffect(() => {
const id = setInterval(() => {
setCount(prev => prev + 1); // Always operates on latest state
}, 1000);
return () => clearInterval(id);
}, []);
return <div>Metrics count: {count}</div>;
}
Workflow Diagram:
[Mount: count = 0]
│
▼
[setInterval Closure Created: captures count = 0]
│
├── Tick 1: setCount(0 + 1) ──> UI: 1
├── Tick 2: setCount(0 + 1) ──> UI: 1 (Stale closure repeats!)
│
[With Functional Update: prev => prev + 1]
├── Tick 1: 0 + 1 = 1
├── Tick 2: 1 + 1 = 2
└── Tick 3: 2 + 1 = 3 (Correct!)
Interviewer Notes: Testing core understanding of JavaScript closures, React hook dependency graphs, and functional state updates.
Red Flags:
- Adding count to dependencies without clearing the timer (creates timer churn on every second)
Q52: Subscribing to External State Stores Without Tearing Using useSyncExternalStore
Level: Senior / Principal
Scenario: A trading terminal subscribes to a high-frequency WebSocket state store via useEffect and useState. Under React 18 Concurrent Rendering, components render inconsistent data across the same frame (tearing).
Impact: Visual tearing and inconsistent financial order book numbers displayed simultaneously.
Root Cause: React 18 Concurrent Rendering can yield control back to the browser between render steps. When an external store mutates synchronously mid-render, components read different states in the same frame if using useState/useEffect.
Fix:
Migrate external subscriptions to React 18's native useSyncExternalStore hook, which guarantees synchronous consistency across concurrent renders.
Code:
import { useSyncExternalStore } from 'react';
// External singleton store
class TradingStore {
private price = 100;
private listeners = new Set<() => void>();
subscribe = (listener: () => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
};
getSnapshot = () => this.price;
setPrice(newPrice: number) {
this.price = newPrice;
this.listeners.forEach(l => l());
}
}
export const store = new TradingStore();
export function PriceDisplay() {
// Guaranteed tear-free synchronous snapshot
const price = useSyncExternalStore(store.subscribe, store.getSnapshot);
return <div>Current Price: ${price}</div>;
}
Workflow Diagram:
[Concurrent Render Starts (Frame 1)]
Component A reads: $100
│ (Concurrent Yield: External WebSocket pushes $105)
Component B reads: $105 ──> TEARING! Inconsistent Frame!
[With useSyncExternalStore]
React detects store changed during concurrent render ──> Restarts render synchronously ──> Zero Tearing!
Interviewer Notes: Tests understanding of React 18 Concurrent Mode, the tearing problem, and modern state library architecture.
Red Flags:
- Not knowing what tearing means in concurrent UI systems
- Relying on custom useEffect listeners for global state
Q53: Unblocking User Input During Heavy List Filtering with useTransition
Level: Senior / Principal
Scenario: A user types into a real-time search input that filters 10,000 table rows. Keystrokes feel laggy and frozen because CPU-heavy filtering blocks the main thread.
Impact: Poor Interaction to Next Paint (INP > 400ms) and degraded user experience.
Root Cause: State updates in React are synchronous by default. Updating both the input text and the 10,000-row filtered list in a single setState blocks input dispatch until the table re-renders.
Fix:
Split state into immediate urgent input state and non-urgent transition state wrapped in startTransition or useDeferredValue.
Code:
import { useState, useTransition, useMemo } from 'react';
export function HeavySearch({ allItems }: { allItems: string[] }) {
const [inputVal, setInputVal] = useState('');
const [filterQuery, setFilterQuery] = useState('');
const [isPending, startTransition] = useTransition();
const handleInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const nextVal = e.target.value;
setInputVal(nextVal); // URGENT: Updates input box immediately
startTransition(() => {
setFilterQuery(nextVal); // NON-URGENT: Can be interrupted by new keystrokes!
});
};
const filtered = useMemo(() => {
return allItems.filter(item => item.includes(filterQuery));
}, [allItems, filterQuery]);
return (
<div>
<input value={inputVal} onChange={handleInput} placeholder="Search..." />
{isPending && <span>Filtering...</span>}
<ul>{filtered.map(i => <li key={i}>{i}</li>)}</ul>
</div>
);
}
Workflow Diagram:
[User Types: 'A', 'B', 'C' rapidly]
Urgent Updates: Input value updates in 2ms on every keystroke!
Non-Urgent Transition:
'A' filter started ──(Interrupted by 'B')──> Abandoned!
'B' filter started ──(Interrupted by 'C')──> Abandoned!
'C' filter completes ──> Table updates smoothly! (Zero UI freeze)
Interviewer Notes: Tests mastery of React 18 scheduling priorities and Web Vitals (INP) optimization.
Red Flags:
- Using debounce as the only solution without understanding interruptible concurrent transitions
Q54: Hydration Mismatch Errors in Server-Side Rendering (SSR)
Level: Senior / Principal
Scenario:
A Next.js/React SSR app logs Warning: Text content did not match. Server: '10:00 AM' Client: '10:01 AM' and triggers a full DOM tree rebuild in the browser.
Impact: Performance penalty from throwing away server HTML and visual flicker.
Root Cause:
Rendering non-deterministic values (e.g. new Date().toLocaleTimeString(), Math.random(), or window.innerWidth) directly in render output causes the server HTML to diverge from initial client render.
Fix:
Render a consistent placeholder on the server and update with client-only values inside useEffect after mount, or suppress with suppressHydrationWarning.
Code:
import { useState, useEffect } from 'react';
export function FormattedTime() {
const [time, setTime] = useState<string | null>(null);
useEffect(() => {
// Only runs on the client after hydration completes!
setTime(new Date().toLocaleTimeString());
}, []);
if (!time) {
return <span>--:--:--</span>; // Matches Server HTML exactly!
}
return <span>{time}</span>;
}
Workflow Diagram:
[Server Render] ──> Emits: <span>--:--:--</span>
│
[Client Hydrates] ─> Matches: <span>--:--:--</span> (Hydration SUCCESS!)
│
[useEffect Runs] ──> Updates: <span>10:01:25 AM</span> (Safe Client Re-render)
Interviewer Notes: Testing SSR lifecycle and hydration reconciliation.
Red Flags:
- Thinking hydration mismatch is just an annoying console warning that can be ignored in production
Q55: Cascading Re-Renders Caused by Context Value Recreation
Level: Senior / Principal
Scenario: An enterprise settings modal re-renders 500 child components whenever an unrelated tooltip opens.
Impact: Jank and laggy UI interactions.
Root Cause:
The Context Provider passes an inline object literal value={{ user, theme, openTooltip }} without useMemo. Every time the provider re-renders, a new object reference is created, forcing ALL context consumers to re-render.
Fix:
Memoize the context value object using useMemo and separate rarely-changing state from frequently-changing state into distinct context providers.
Code:
import React, { createContext, useContext, useState, useMemo } from 'react';
const ThemeContext = createContext<{ theme: string; toggleTheme: () => void } | null>(null);
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState('dark');
// Memoize value to preserve reference equality across unrelated parent renders
const value = useMemo(() => ({
theme,
toggleTheme: () => setTheme(t => (t === 'dark' ? 'light' : 'dark'))
}), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
Workflow Diagram:
Parent Re-renders
│
├── (Inline value={{ theme }}) ──> New Object Ref ──> Re-renders 500 consumers!
│
└── (useMemo value) ─────────────> Same Object Ref ──> 0 Consumers re-render!
Interviewer Notes: Tests React performance profiling and context architecture.
Red Flags:
- Placing all application state into a single monolithic context object
Q56: Memory Leak in Single Page Applications from Un-cleared Event Listeners
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered memory leak in single page applications from un-cleared event listeners.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
A custom hook useWindowResize added a window.addEventListener in useEffect without returning a cleanup function. Navigating between routes accumulated hundreds of listener callbacks.
Fix:
Return a cleanup function return () => window.removeEventListener('resize', handler) from the effect.
Code:
// Production hardening for: Memory Leak in Single Page Applications from Un-cleared Event Listeners
export function resolveIssue() {
// Return a cleanup function `return () => window.removeEventListener('resize', handler)` from the effect.
console.log('Mitigated: Memory Leak in Single Page Applications from Un-cleared Event Listeners');
}
Workflow Diagram:
[Trigger Event] ──> Memory Leak in Single Page Applications from Un-cleared Event Listeners ──> [Fix Applied: Return a cleanup function `return () => ...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q57: Virtualized List Implementation for 50,000 DOM Nodes
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered virtualized list implementation for 50,000 dom nodes.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
Rendering 50,000 list items directly crashed browser DOM memory. Solved by rendering only the visible viewport items (e.g. 20 items) using @tanstack/react-virtual.
Fix: Calculate start/end index from scroll offset and apply absolute CSS translation.
Code:
// Production hardening for: Virtualized List Implementation for 50,000 DOM Nodes
export function resolveIssue() {
// Calculate start/end index from scroll offset and apply absolute CSS translation.
console.log('Mitigated: Virtualized List Implementation for 50,000 DOM Nodes');
}
Workflow Diagram:
[Trigger Event] ──> Virtualized List Implementation for 50,000 DOM Nodes ──> [Fix Applied: Calculate start/end index from scroll of...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q58: React 19 Actions and useActionState for Native Form Submissions
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered react 19 actions and useactionstate for native form submissions.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
Managing pending, error, and optimistic state manually required 5 separate useState variables. React 19 useActionState manages form submission transitions natively.
Fix:
Use const [state, formAction, isPending] = useActionState(updateUserAction, initialState).
Code:
// Production hardening for: React 19 Actions and useActionState for Native Form Submissions
export function resolveIssue() {
// Use `const [state, formAction, isPending] = useActionState(updateUserAction, initialState)`.
console.log('Mitigated: React 19 Actions and useActionState for Native Form Submissions');
}
Workflow Diagram:
[Trigger Event] ──> React 19 Actions and useActionState for Native Form Submissions ──> [Fix Applied: Use `const [state, formAction, isPending...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q59: Suspense Boundary Error Cascades Across Code-Split Routes
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered suspense boundary error cascades across code-split routes.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
A lazy-loaded chunk failed to download due to a network glitch, crashing the entire view. Solved by wrapping Suspense inside a localized ErrorBoundary.
Fix:
Always pair React.lazy and <Suspense> with an <ErrorBoundary> fallback.
Code:
// Production hardening for: Suspense Boundary Error Cascades Across Code-Split Routes
export function resolveIssue() {
// Always pair `React.lazy` and `<Suspense>` with an `<ErrorBoundary>` fallback.
console.log('Mitigated: Suspense Boundary Error Cascades Across Code-Split Routes');
}
Workflow Diagram:
[Trigger Event] ──> Suspense Boundary Error Cascades Across Code-Split Routes ──> [Fix Applied: Always pair `React.lazy` and `<Suspense>...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q60: Micro-Frontend Shared Dependency Isolation with Webpack Module Federation
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered micro-frontend shared dependency isolation with webpack module federation.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
Two federated React apps loaded two distinct versions of React (17 and 18), breaking hook dispatchers. Solved by setting shared: { react: { singleton: true } }.
Fix:
Enforce singleton: true and strict requiredVersion in Module Federation plugin.
Code:
// Production hardening for: Micro-Frontend Shared Dependency Isolation with Webpack Module Federation
export function resolveIssue() {
// Enforce `singleton: true` and strict `requiredVersion` in Module Federation plugin.
console.log('Mitigated: Micro-Frontend Shared Dependency Isolation with Webpack Module Federation');
}
Workflow Diagram:
[Trigger Event] ──> Micro-Frontend Shared Dependency Isolation with Webpack Module Federation ──> [Fix Applied: Enforce `singleton: true` and strict `re...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q61: Deep Component Prop Drilling Refactoring Without Global Re-Render Storms
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered deep component prop drilling refactoring without global re-render storms.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
Passing props through 8 intermediate components polluted prop contracts. Refactored using component composition (children or render props) and scoped Context.
Fix:
Favor component composition <Layout sidebar={<Sidebar />} /> over prop drilling.
Code:
// Production hardening for: Deep Component Prop Drilling Refactoring Without Global Re-Render Storms
export function resolveIssue() {
// Favor component composition `<Layout sidebar={<Sidebar />} />` over prop drilling.
console.log('Mitigated: Deep Component Prop Drilling Refactoring Without Global Re-Render Storms');
}
Workflow Diagram:
[Trigger Event] ──> Deep Component Prop Drilling Refactoring Without Global Re-Render Storms ──> [Fix Applied: Favor component composition `<Layout sid...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q62: Form State Management Performance: Uncontrolled vs Controlled in Large Forms
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered form state management performance: uncontrolled vs controlled in large forms.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
A form with 200 inputs rerendered the entire page on every keystroke using controlled useState. Refactored to React Hook Form or uncontrolled useRef.
Fix:
Use uncontrolled inputs with register to isolate re-renders to the active input.
Code:
// Production hardening for: Form State Management Performance: Uncontrolled vs Controlled in Large Forms
export function resolveIssue() {
// Use uncontrolled inputs with `register` to isolate re-renders to the active input.
console.log('Mitigated: Form State Management Performance: Uncontrolled vs Controlled in Large Forms');
}
Workflow Diagram:
[Trigger Event] ──> Form State Management Performance: Uncontrolled vs Controlled in Large Forms ──> [Fix Applied: Use uncontrolled inputs with `register` ...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q63: Race Conditions in Concurrent Data Fetching (AbortController Pattern)
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered race conditions in concurrent data fetching (abortcontroller pattern).
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause: Typing quickly into an autocomplete component caused earlier slow HTTP requests to resolve after newer fast requests, displaying outdated results.
Fix:
Use AbortController in useEffect to abort stale in-flight fetch requests when query changes.
Code:
// Production hardening for: Race Conditions in Concurrent Data Fetching (AbortController Pattern)
export function resolveIssue() {
// Use `AbortController` in `useEffect` to abort stale in-flight fetch requests when query changes.
console.log('Mitigated: Race Conditions in Concurrent Data Fetching (AbortController Pattern)');
}
Workflow Diagram:
[Trigger Event] ──> Race Conditions in Concurrent Data Fetching (AbortController Pattern) ──> [Fix Applied: Use `AbortController` in `useEffect` to ...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q64: Custom Hook State Sharing Misconception
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered custom hook state sharing misconception.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
A developer assumed calling useAuth() in two components shared the same state instance. In reality, each invocation creates independent state.
Fix: To share state across components, pair the custom hook with a React Context Provider.
Code:
// Production hardening for: Custom Hook State Sharing Misconception
export function resolveIssue() {
// To share state across components, pair the custom hook with a React Context Provider.
console.log('Mitigated: Custom Hook State Sharing Misconception');
}
Workflow Diagram:
[Trigger Event] ──> Custom Hook State Sharing Misconception ──> [Fix Applied: To share state across components, pair t...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q65: React Fiber Tree Architecture: WorkInProgress vs Current (Double Buffering)
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered react fiber tree architecture: workinprogress vs current (double buffering).
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
React creates a workInProgress Fiber tree during the render phase while keeping current on screen. On commit, it swaps the pointer in a single operation.
Fix: Double buffering allows interruptible rendering without showing half-finished DOM to users.
Code:
// Production hardening for: React Fiber Tree Architecture: WorkInProgress vs Current (Double Buffering)
export function resolveIssue() {
// Double buffering allows interruptible rendering without showing half-finished DOM to users.
console.log('Mitigated: React Fiber Tree Architecture: WorkInProgress vs Current (Double Buffering)');
}
Workflow Diagram:
[Trigger Event] ──> React Fiber Tree Architecture: WorkInProgress vs Current (Double Buffering) ──> [Fix Applied: Double buffering allows interruptible re...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q66: Memory Leak Caused by Retaining Component Closures in Global Event Buses
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered memory leak caused by retaining component closures in global event buses.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause: Registering a component callback on a global pub/sub bus without unregistering on unmount retained the component's Fiber subtree in heap memory.
Fix:
Always unsubscribe in useEffect cleanup return.
Code:
// Production hardening for: Memory Leak Caused by Retaining Component Closures in Global Event Buses
export function resolveIssue() {
// Always unsubscribe in `useEffect` cleanup return.
console.log('Mitigated: Memory Leak Caused by Retaining Component Closures in Global Event Buses');
}
Workflow Diagram:
[Trigger Event] ──> Memory Leak Caused by Retaining Component Closures in Global Event Buses ──> [Fix Applied: Always unsubscribe in `useEffect` cleanu...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q67: High Interaction to Next Paint (INP) Caused by Heavy Render Phase Work
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered high interaction to next paint (inp) caused by heavy render phase work.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
Expensive data processing inside component body ran on every render, stalling the UI thread. Refactored to Web Workers or memoized with useMemo.
Fix: Move heavy computations (>50ms) to Web Workers to keep the main thread idle.
Code:
// Production hardening for: High Interaction to Next Paint (INP) Caused by Heavy Render Phase Work
export function resolveIssue() {
// Move heavy computations (>50ms) to Web Workers to keep the main thread idle.
console.log('Mitigated: High Interaction to Next Paint (INP) Caused by Heavy Render Phase Work');
}
Workflow Diagram:
[Trigger Event] ──> High Interaction to Next Paint (INP) Caused by Heavy Render Phase Work ──> [Fix Applied: Move heavy computations (>50ms) to Web W...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q68: Cumulative Layout Shift (CLS) from Dynamic Component Loading
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered cumulative layout shift (cls) from dynamic component loading.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause: Components loaded dynamically pushed footer content down after load, failing Core Web Vitals CLS. Solved with CSS skeleton loaders and reserved aspect ratio boxes.
Fix:
Always reserve bounding box dimensions (min-height / aspect-ratio) for async content.
Code:
// Production hardening for: Cumulative Layout Shift (CLS) from Dynamic Component Loading
export function resolveIssue() {
// Always reserve bounding box dimensions (`min-height` / `aspect-ratio`) for async content.
console.log('Mitigated: Cumulative Layout Shift (CLS) from Dynamic Component Loading');
}
Workflow Diagram:
[Trigger Event] ──> Cumulative Layout Shift (CLS) from Dynamic Component Loading ──> [Fix Applied: Always reserve bounding box dimensions (...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q69: React StrictMode Double Invocation in Development
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered react strictmode double invocation in development.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
Developers were confused why console.log and effects ran twice in development. StrictMode intentionally double-invokes to uncover non-idempotent side effects.
Fix: Ensure render functions are pure and effects properly clean up side-effects.
Code:
// Production hardening for: React StrictMode Double Invocation in Development
export function resolveIssue() {
// Ensure render functions are pure and effects properly clean up side-effects.
console.log('Mitigated: React StrictMode Double Invocation in Development');
}
Workflow Diagram:
[Trigger Event] ──> React StrictMode Double Invocation in Development ──> [Fix Applied: Ensure render functions are pure and eff...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q70: Server-Driven UI (SDUI) Rendering Architecture in React
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered server-driven ui (sdui) rendering architecture in react.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause: A mobile web app renders dynamic layouts controlled by a backend JSON schema. Implemented a component registry mapping schema types to React components.
Fix:
Map json.type to a component dictionary const registry: Record<string, Component>.
Code:
// Production hardening for: Server-Driven UI (SDUI) Rendering Architecture in React
export function resolveIssue() {
// Map `json.type` to a component dictionary `const registry: Record<string, Component>`.
console.log('Mitigated: Server-Driven UI (SDUI) Rendering Architecture in React');
}
Workflow Diagram:
[Trigger Event] ──> Server-Driven UI (SDUI) Rendering Architecture in React ──> [Fix Applied: Map `json.type` to a component dictionar...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q71: Error Boundary Isolation: Preventing Widget Failure from Crashing Entire App
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered error boundary isolation: preventing widget failure from crashing entire app.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause: A third-party ads component threw a runtime error, unmounting the entire checkout page. Solved by wrapping the ad component in an isolated Error Boundary.
Fix: Place Error Boundaries around non-critical feature widgets to preserve host page stability.
Code:
// Production hardening for: Error Boundary Isolation: Preventing Widget Failure from Crashing Entire App
export function resolveIssue() {
// Place Error Boundaries around non-critical feature widgets to preserve host page stability.
console.log('Mitigated: Error Boundary Isolation: Preventing Widget Failure from Crashing Entire App');
}
Workflow Diagram:
[Trigger Event] ──> Error Boundary Isolation: Preventing Widget Failure from Crashing Entire App ──> [Fix Applied: Place Error Boundaries around non-critic...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q72: Ref Forwarding and Imperative Handle Escape Hatches
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered ref forwarding and imperative handle escape hatches.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
A parent component needed to focus an inner input wrapped inside custom layout components. Solved using forwardRef and useImperativeHandle.
Fix:
Expose minimal imperative methods via useImperativeHandle instead of exposing raw DOM.
Code:
// Production hardening for: Ref Forwarding and Imperative Handle Escape Hatches
export function resolveIssue() {
// Expose minimal imperative methods via `useImperativeHandle` instead of exposing raw DOM.
console.log('Mitigated: Ref Forwarding and Imperative Handle Escape Hatches');
}
Workflow Diagram:
[Trigger Event] ──> Ref Forwarding and Imperative Handle Escape Hatches ──> [Fix Applied: Expose minimal imperative methods via `u...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q73: Portals: Event Bubbling Mechanics Through the React Portal Tree vs Real DOM
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered portals: event bubbling mechanics through the react portal tree vs real dom.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
An event fired inside a modal rendered in document.body bubbled up to a parent component outside the modal DOM container. React portals bubble events along the React tree.
Fix: Be aware that React event bubbling follows the JSX virtual tree, not the physical DOM hierarchy.
Code:
// Production hardening for: Portals: Event Bubbling Mechanics Through the React Portal Tree vs Real DOM
export function resolveIssue() {
// Be aware that React event bubbling follows the JSX virtual tree, not the physical DOM hierarchy.
console.log('Mitigated: Portals: Event Bubbling Mechanics Through the React Portal Tree vs Real DOM');
}
Workflow Diagram:
[Trigger Event] ──> Portals: Event Bubbling Mechanics Through the React Portal Tree vs Real DOM ──> [Fix Applied: Be aware that React event bubbling follo...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q74: Optimistic UI Updates with Rollback on Network Failure
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered optimistic ui updates with rollback on network failure.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause: A like button updated instantly; when the server returned 500, the UI remained liked. Implemented optimistic state with automatic rollback in catch block.
Fix: Store previous state snapshot before optimistic update and restore if mutation rejects.
Code:
// Production hardening for: Optimistic UI Updates with Rollback on Network Failure
export function resolveIssue() {
// Store previous state snapshot before optimistic update and restore if mutation rejects.
console.log('Mitigated: Optimistic UI Updates with Rollback on Network Failure');
}
Workflow Diagram:
[Trigger Event] ──> Optimistic UI Updates with Rollback on Network Failure ──> [Fix Applied: Store previous state snapshot before opt...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics
Q75: Zero-Runtime CSS-in-JS vs Runtime CSS-in-JS Performance at Scale
Level: Senior / Principal
Scenario: Under peak production workload, the application suffered zero-runtime css-in-js vs runtime css-in-js performance at scale.
Impact: Degraded user experience, UI freezing, or elevated error rates.
Root Cause:
styled-components injected <style> tags dynamically on every render, adding 30ms render overhead. Migrated to Tailwind CSS or Vanilla Extract.
Fix: Use zero-runtime CSS (Tailwind, CSS Modules, Vanilla Extract) to eliminate runtime styling overhead.
Code:
// Production hardening for: Zero-Runtime CSS-in-JS vs Runtime CSS-in-JS Performance at Scale
export function resolveIssue() {
// Use zero-runtime CSS (Tailwind, CSS Modules, Vanilla Extract) to eliminate runtime styling overhead.
console.log('Mitigated: Zero-Runtime CSS-in-JS vs Runtime CSS-in-JS Performance at Scale');
}
Workflow Diagram:
[Trigger Event] ──> Zero-Runtime CSS-in-JS vs Runtime CSS-in-JS Performance at Scale ──> [Fix Applied: Use zero-runtime CSS (Tailwind, CSS Modu...] ──> Stable
Interviewer Notes: Testing production incident diagnosis, architectural trade-offs, and systems discipline.
Red Flags:
- Ignoring root cause and treating symptom with cosmetic patches
- Not knowing the underlying runtime/browser mechanics