React
Rendering fundamentals
Section titled “Rendering fundamentals”Q (basic): What is the virtual DOM and how does reconciliation work?
Say this (30 sec): The virtual DOM is a lightweight JS object tree describing the UI. When state changes, React re-runs components to build a new tree, diffs it against the previous one, and applies only the minimal changes to the real DOM — that’s reconciliation. The diffing uses two heuristics to stay O(n): if the element type changes (e.g. div → span, or ComponentA → ComponentB), React throws away that subtree and rebuilds it; and in lists, keys identify which item is which.
Follow-ups they ask: Is the virtual DOM faster than the real DOM? → Not inherently; it’s a way to write declarative code with good enough performance by batching and minimizing DOM writes. What is Fiber? → React’s internal reconciler (since React 16) that splits rendering into units of work so it can pause, prioritize and resume — enabling concurrent features like transitions.
Common wrong answer: “React re-renders the whole real DOM.” It re-runs components (the render phase) but only touches changed DOM nodes in the commit phase.
Q (basic): Why are keys needed? Why not use index as key?
Say this (30 sec): Keys let React match list items between renders. With stable keys, React can reorder, insert or remove items efficiently and keep each item’s state attached to the right item. Using the index breaks when the list is reordered, filtered or has items inserted at the start — state (like input text or checkbox) sticks to the position, not the item. Index is fine only for static lists that never change order.
Example:
{todos.map((todo) => <TodoItem key={todo.id} todo={todo} />)}Follow-ups they ask: Trick with keys? → changing a component’s key forces React to remount it with fresh state, e.g. <ProfileForm key={userId} /> resets the form when the user changes.
Q (basic): State vs props?
Say this (30 sec): Props are inputs passed from the parent — read-only for the child. State is data a component owns and can change over time with a setter; changing it triggers a re-render. Data flows one way: down via props, and children communicate up by calling callback props.
Example:
function Parent() { const [count, setCount] = useState(0); // state return <Child count={count} onInc={() => setCount(c => c + 1)} />; // props}function Child({ count, onInc }) { return <button onClick={onInc}>{count}</button>;}Q (mid): What causes a component to re-render?
Say this (30 sec): Three things: (1) its own state changes, (2) its parent re-renders — by default all children re-render even if props are the same, (3) a context it consumes changes value. Also, a Zustand/Redux selector it subscribes to returning a new value. If you set state to the same value (Object.is equal), React bails out.
Follow-ups they ask: How to stop unnecessary child re-renders? → React.memo with stable props, move state down closer to where it’s used, or pass components as children so they’re created by a parent that doesn’t re-render.
Common wrong answer: “A component re-renders only when its props change.” Without memo, it re-renders whenever the parent does.
Q (mid): Is setState synchronous? What is batching?
Say this (30 sec): State updates are not applied immediately — the new value is available on the next render, so reading state right after setState gives the old value. Since React 18, all updates are automatically batched — in event handlers, promises, timeouts — into a single re-render. When the next state depends on the previous one, use the updater function.
Example:
const handleClick = () => { setCount(count + 1); setCount(count + 1); console.log(count); // still old value}; // result: +1, not +2
const handleClick2 = () => { setCount(c => c + 1); setCount(c => c + 1); // result: +2};Q (mid): Why must state be updated immutably?
Say this (30 sec): React compares old and new state by reference (Object.is). If you mutate an array/object and pass the same reference, React thinks nothing changed and skips the re-render. Memo and selectors also rely on new references. So always create new objects/arrays.
Example:
// wrongtodos.push(newTodo); setTodos(todos);
// rightsetTodos([...todos, newTodo]);setTodos(todos.map(t => t.id === id ? { ...t, done: !t.done } : t));setTodos(todos.filter(t => t.id !== id));setUser(u => ({ ...u, address: { ...u.address, city: "Pune" } }));Q (basic): What are the rules of hooks and why do they exist?
Say this (30 sec): (1) Only call hooks at the top level — not in conditions, loops, or after an early return. (2) Only call them from React function components or custom hooks. The reason: React stores hook state in an ordered list per component and matches them by call order on every render. If the order changes between renders, state gets attached to the wrong hook.
Follow-ups they ask: Exception? → React 19’s use() can be called conditionally. Enforced by? → eslint-plugin-react-hooks.
Q (basic): Explain useEffect, its dependency array and cleanup.
Say this (30 sec): useEffect runs after the component renders and the browser paints. It’s for syncing with external systems — fetching, subscriptions, timers, DOM APIs. The dependency array controls when it re-runs: no array → after every render; [] → once after mount; [a, b] → when a or b change (compared with Object.is). The returned cleanup runs before the effect re-runs and on unmount.
Example:
useEffect(() => { const controller = new AbortController(); fetch(`/api/users/${id}`, { signal: controller.signal }) .then(r => r.json()) .then(setUser) .catch(err => { if (err.name !== "AbortError") setError(err); }); return () => controller.abort(); // cancels stale request when id changes}, [id]);Follow-ups they ask: Why does my effect run in a loop? → it sets state that’s in its deps, or a dep is an object/function recreated every render. Should you lie about deps? → No; fix the root cause (move the function inside the effect, use updater functions, or useEffectEvent in React 19.2).
Q (mid): When should you NOT use useEffect?
Say this (30 sec): Don’t use effects to compute data from props/state — calculate it during render. Don’t use them to handle user events — put that logic in the event handler. Don’t use them to reset state on prop change — use a key. Unnecessary effects cause extra renders and bugs.
Example:
// badconst [fullName, setFullName] = useState("");useEffect(() => setFullName(`${first} ${last}`), [first, last]);
// goodconst fullName = `${first} ${last}`;Q (mid): useEffect vs useLayoutEffect?
Say this (30 sec): useEffect runs after paint — non-blocking, right for most cases. useLayoutEffect runs synchronously after DOM changes but before paint, so you can measure layout (e.g. tooltip position) and update without a visible flicker. It blocks painting, so use it only when needed. With GSAP in React, useGSAP / useLayoutEffect is used so animations set initial styles before the first paint.
Q (basic): What is useRef used for?
Say this (30 sec): useRef gives a mutable box { current } that persists across renders without causing a re-render when changed. Two uses: (1) referencing DOM nodes — focus, measure, attach GSAP or a library; (2) storing mutable values like timer IDs, previous values, a Howler sound instance, or an AbortController.
Example:
const inputRef = useRef(null);const timerRef = useRef(null);
useEffect(() => { inputRef.current?.focus(); }, []);
const start = () => { timerRef.current = setInterval(tick, 1000); };const stop = () => clearInterval(timerRef.current);
return <input ref={inputRef} />;Follow-ups they ask: Why not a normal variable? → it resets every render. Why not state? → changing it would re-render unnecessarily. Don’t read/write ref.current during render (except lazy init).
Q (mid): useMemo vs useCallback vs React.memo — and when NOT to use them?
Say this (30 sec): useMemo caches a computed value; useCallback caches a function reference; React.memo wraps a component to skip re-render if props are shallow-equal. They only help when: the computation is genuinely expensive, or you pass a value/function to a memo child or into an effect’s deps. Don’t use them everywhere — they add memory and comparison cost, and useCallback without a memoized child does nothing useful. With the React Compiler enabled, it does this memoization automatically, so manual usage is mostly unnecessary.
Example:
const filtered = useMemo(() => bigList.filter(matches(query)), [bigList, query]);const handleSelect = useCallback((id) => setSelected(id), []);const Row = React.memo(function Row({ item, onSelect }) { /* ... */ });Common wrong answer: “useCallback makes the function faster / prevents it from being recreated.” The function is still created each render; React just returns the cached one.
Q (mid): useState vs useReducer?
Say this (30 sec): useState for simple independent values. useReducer when state has multiple related fields or the next state depends on complex logic — all transitions live in one pure reducer function, easier to test and reason about, and dispatch is stable.
Example:
function reducer(state, action) { switch (action.type) { case "add": return { ...state, items: [...state.items, action.item] }; case "remove": return { ...state, items: state.items.filter(i => i.id !== action.id) }; default: return state; }}const [state, dispatch] = useReducer(reducer, { items: [] });Q (basic): What is a custom hook? Give an example.
Say this (30 sec): A function starting with use that calls other hooks, to reuse stateful logic between components. Each component using it gets its own state — hooks share logic, not state.
Example:
function useDebounce(value, delay = 300) { const [debounced, setDebounced] = useState(value); useEffect(() => { const id = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(id); }, [value, delay]); return debounced;}
function useLocalStorage(key, initial) { const [value, setValue] = useState(() => { const saved = localStorage.getItem(key); return saved ? JSON.parse(saved) : initial; }); useEffect(() => localStorage.setItem(key, JSON.stringify(value)), [key, value]); return [value, setValue];}Follow-ups they ask: Lazy initial state? → passing a function to useState(() => ...) runs it only on the first render (good for reading localStorage). In Next.js, localStorage doesn’t exist on the server, so read it in an effect or in a client-only component.
Forms and component patterns
Section titled “Forms and component patterns”Q (basic): Controlled vs uncontrolled components?
Say this (30 sec): A controlled input’s value lives in React state — value + onChange — so React is the source of truth; good for live validation and dependent fields. An uncontrolled input keeps its value in the DOM; you read it via a ref or FormData on submit. Uncontrolled is simpler and re-renders less; React 19 form actions work naturally with uncontrolled inputs + FormData. React Hook Form is mostly uncontrolled for performance.
Example:
// controlledconst [email, setEmail] = useState("");<input value={email} onChange={(e) => setEmail(e.target.value)} />
// uncontrolled<form onSubmit={(e) => { e.preventDefault(); const data = new FormData(e.currentTarget); console.log(data.get("email"));}}> <input name="email" defaultValue="" /></form>Common wrong answer: Switching value from undefined to a string — React warns “changing an uncontrolled input to be controlled.” Always initialize with "".
Q (basic): What is lifting state up? What is prop drilling?
Say this (30 sec): When two siblings need the same data, move the state to their closest common parent and pass it down — that’s lifting state up. Prop drilling is when you pass props through many layers that don’t use them just to reach a deep child. Fixes: component composition (pass children), Context, or a store like Zustand.
Q (mid): How do forms work with React 19 actions?
Say this (30 sec): You can pass a function to <form action={fn}>. React calls it with FormData, wraps it in a transition, and resets uncontrolled fields after success. useActionState gives you the returned state and a pending flag; useFormStatus lets a child (like a submit button) read the parent form’s pending state. In Next.js, the action can be a server action.
Example:
async function signup(prevState, formData) { const email = formData.get("email"); if (!email) return { error: "Email required" }; await api.signup(email); return { error: null };}
function SignupForm() { const [state, formAction, isPending] = useActionState(signup, { error: null }); return ( <form action={formAction}> <input name="email" /> <button disabled={isPending}>{isPending ? "Saving..." : "Sign up"}</button> {state.error && <p>{state.error}</p>} </form> );}Q (mid): What are error boundaries? What don't they catch?
Say this (30 sec): An error boundary catches JavaScript errors during rendering, in lifecycle methods and constructors of its children, and shows a fallback UI instead of unmounting the whole app. They’re still class components (getDerivedStateFromError, componentDidCatch), or you use the react-error-boundary library. They do not catch errors in event handlers, async code (setTimeout, promises), SSR, or in the boundary itself. In Next.js, error.tsx is an error boundary per route segment.
Example:
class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error, info) { logToService(error, info); } render() { return this.state.hasError ? <p>Something went wrong</p> : this.props.children; }}Q (mid): What is a portal? When would you use it?
Say this (30 sec): createPortal(children, domNode) renders children into a different DOM node (like document.body) while keeping them in the same React tree — so context and event bubbling still work through the React parent. Used for modals, tooltips, dropdowns and toasts to escape overflow: hidden and z-index stacking issues.
State management
Section titled “State management”Q (mid): Context vs Zustand vs Redux — when to use which?
Say this (30 sec):
- Context is dependency injection, not a state manager. Great for low-frequency values: theme, auth user, locale. Every consumer re-renders when the value changes, so it’s bad for fast-changing state.
- Zustand — tiny store with hooks, no provider, components subscribe to slices via selectors and re-render only when that slice changes. Great default for client UI state in small/medium apps.
- Redux Toolkit — more structure: actions, reducers, middleware, great devtools, RTK Query. Suits large teams and complex flows.
- Server data (API responses) should go in TanStack Query / SWR / Next.js server components, not in a global store.
Follow-ups they ask: Why did you choose Zustand? → Minimal boilerplate, no provider wrapping, selector-based subscriptions avoid unnecessary re-renders, and the store can be read/updated outside React (e.g. from a GSAP callback or a Howler event).
Q (mid): Explain how Zustand works with an example.
Say this (30 sec): You create a store with create, which returns a hook. The store holds state plus actions; set merges updates (shallowly) and get reads current state. Components call the hook with a selector, and Zustand re-renders that component only if the selected value changes (compared with Object.is). Under the hood it uses React’s useSyncExternalStore.
Example:
import { create } from "zustand";import { persist } from "zustand/middleware";import { useShallow } from "zustand/react/shallow";
type CartState = { items: { id: string; qty: number }[]; add: (id: string) => void; clear: () => void;};
export const useCart = create<CartState>()( persist( (set) => ({ items: [], add: (id) => set((s) => ({ items: [...s.items, { id, qty: 1 }] })), clear: () => set({ items: [] }), }), { name: "cart" } // saved to localStorage ));
// in components — select only what you needconst count = useCart((s) => s.items.length);const { add, clear } = useCart(useShallow((s) => ({ add: s.add, clear: s.clear })));
// outside ReactuseCart.getState().clear();Follow-ups they ask: Why useShallow? → a selector returning a new object every time would always look “changed” (and in Zustand v5 can cause an infinite loop); useShallow compares its keys shallowly. Pitfall: const state = useCart() with no selector subscribes to everything. Next.js caveat: a module-level store is shared across requests on the server, so for SSR’d per-user data create the store per request via a Context provider.
Q (mid): How do you avoid Context causing too many re-renders?
Say this (30 sec): Split contexts by concern (e.g. separate state and dispatch contexts), memoize the provider value with useMemo so it doesn’t change every render, keep the provider low in the tree, and move fast-changing state to a store with selectors (Zustand).
Example:
const value = useMemo(() => ({ user, login, logout }), [user]);return <AuthContext value={value}>{children}</AuthContext>; // React 19: Context as providerPerformance
Section titled “Performance”Q (mid): How do you optimize a slow React app?
Say this (30 sec): First measure with React DevTools Profiler and Chrome Performance tab — don’t guess. Then, common fixes:
- Move state down / split components so fewer things re-render.
React.memo+ stable props for expensive children (or enable React Compiler).- Virtualize long lists (TanStack Virtual, react-window).
- Code-split with
React.lazy+Suspense/next/dynamic. - Debounce inputs; use
useTransition/useDeferredValueto keep typing responsive. - Use selectors in Zustand instead of subscribing to the whole store.
- Optimize images and bundle size (check for huge libraries).
Q (mid): What are useTransition and useDeferredValue?
Say this (30 sec): Both mark updates as non-urgent so urgent ones (typing, clicking) stay responsive. useTransition wraps a state update you control: startTransition(() => setTab(next)) and gives isPending. useDeferredValue takes a value and gives a “lagging” copy for expensive rendering, useful when you don’t control the setter. They don’t debounce — React renders the urgent update first and interrupts the slow one if new input arrives.
Example:
const [query, setQuery] = useState("");const deferredQuery = useDeferredValue(query);const results = useMemo(() => search(deferredQuery), [deferredQuery]);Q (basic): What is lazy loading components with React.lazy?
Say this (30 sec): React.lazy(() => import("./Heavy")) splits the component into a separate chunk loaded only when it first renders. Wrap it in <Suspense fallback> to show a loader while it downloads. Good for routes, modals, charts, editors.
Example:
const Chart = lazy(() => import("./Chart"));<Suspense fallback={<Spinner />}>{showChart && <Chart />}</Suspense>Suspense, StrictMode and React 19
Section titled “Suspense, StrictMode and React 19”Q (mid): What is Suspense?
Say this (30 sec): Suspense lets a component “wait” for something — lazy code or data — and shows a fallback until it’s ready. Data fetching works with Suspense-enabled sources: React 19’s use(promise), server components in Next.js, TanStack Query’s useSuspenseQuery. In Next.js, loading.tsx is an automatic Suspense boundary and Suspense enables streaming: the shell is sent first and slow parts stream in later.
Q (mid): Why does my useEffect run twice in development?
Say this (30 sec): That’s StrictMode. In development only, React mounts, immediately unmounts, and remounts components to run effects twice — and also double-calls component functions and reducers — to expose missing cleanups and impure renders. It doesn’t happen in production. The fix isn’t to remove StrictMode but to write a proper cleanup (abort the fetch, remove the listener, clear the timer, stop the Howler sound).
Common wrong answer: “It’s a bug, use a ref flag to skip the second call.” That hides the real problem.
Q (mid): What's new in React 19?
Say this (30 sec):
- Actions: async functions in transitions handle pending, errors and form resets. Hooks:
useActionState,useFormStatus,useOptimistic. use(): reads a promise (suspends) or context; can be called conditionally.refas a prop — no moreforwardReffor function components; ref callbacks can return a cleanup.<Context>directly as provider instead of<Context.Provider>.- Document metadata:
<title>,<meta>,<link>rendered anywhere get hoisted to<head>. - Server Components and Server Actions are stable (used via frameworks like Next.js).
- React Compiler (1.0 stable in 2025) — build-time auto-memoization.
- React 19.2 added
<Activity>(hide/show UI while keeping state) anduseEffectEvent.
Example:
function LikeButton({ likes, onLike }) { const [optimistic, addOptimistic] = useOptimistic(likes, (cur, inc) => cur + inc); return ( <form action={async () => { addOptimistic(1); await onLike(); }}> <button>{optimistic} likes</button> </form> );}
function Input({ ref, ...props }) { return <input ref={ref} {...props} />; } // no forwardRefQ (mid): What does the React Compiler do?
Say this (30 sec): It’s a build-time Babel plugin that analyzes your components and automatically inserts memoization — similar to wrapping values in useMemo, functions in useCallback, and components in memo, but more fine-grained. It requires your code to follow the Rules of React (pure renders, no mutating props/state). Next.js supports it via the reactCompiler option.
Q (tricky): What is hydration, and what causes hydration mismatch errors?
Say this (30 sec): With SSR, the server sends HTML; on the client React “hydrates” it — attaches event handlers and state to the existing markup instead of re-creating it. If the client’s first render produces different HTML than the server’s, you get a mismatch. Common causes: Date.now()/Math.random() in render, typeof window branches, reading localStorage during render, locale-formatted dates, invalid HTML nesting (<div> inside <p>), and browser extensions. Fix: render browser-only values in useEffect after mount, or load the component client-only.
Libraries from your resume
Section titled “Libraries from your resume”Q (mid): How did you use GSAP in React without memory leaks?
Say this (30 sec): I used the useGSAP hook from @gsap/react. It’s a drop-in for useLayoutEffect that wraps animations in gsap.context() and automatically reverts/kills them on unmount, and I pass a scope ref so selectors only target elements inside my component. Without it, StrictMode’s double-mount creates duplicate tweens and ScrollTriggers leak across route changes. GSAP animates transform and opacity for smooth, GPU-friendly animation.
Example:
import { useGSAP } from "@gsap/react";gsap.registerPlugin(useGSAP);
function Hero() { const container = useRef(null); useGSAP(() => { gsap.from(".title", { y: 40, opacity: 0, duration: 0.8, stagger: 0.1 }); }, { scope: container }); return <section ref={container}><h1 className="title">Hello</h1></section>;}Q (mid): How does React DnD work at a high level?
Say this (30 sec): You wrap the app in a DndProvider with a backend (HTML5 backend for mouse, touch backend for mobile). useDrag makes an item draggable with a type and an item payload; useDrop makes a target that accepts that type and handles drop/hover. Both return a collected state like isDragging/isOver and a ref connector you attach to the DOM node. State changes (reordering) go through normal React state or the store.
Example:
const [{ isDragging }, drag] = useDrag(() => ({ type: "CARD", item: { id }, collect: (m) => ({ isDragging: m.isDragging() }),}));const [, drop] = useDrop(() => ({ accept: "CARD", drop: (item) => moveCard(item.id, targetId) }));Q (mid): How did you manage audio with Howler.js in React?
Say this (30 sec): I created Howl instances once — in a useRef or a module/Zustand store — not on every render, and called .unload() or .stop() in the effect cleanup so sounds don’t keep playing after unmount. Browsers block autoplay until a user gesture, so playback starts from a click handler. Howler uses the Web Audio API with an HTML5 Audio fallback and handles sprites and cross-browser formats.
Example:
const soundRef = useRef(null);useEffect(() => { soundRef.current = new Howl({ src: ["/click.webm", "/click.mp3"] }); return () => soundRef.current?.unload();}, []);const play = () => soundRef.current?.play();