Skip to content

Interview PrepReact · Core

Hooks ​

11. What are hooks, and what are the rules of hooks? ​

The short answer

Hooks are functions whose names start with use that let function components keep state, run side effects and use other React features. There are two rules. Call hooks only at the top level of a component or custom hook, never inside conditions, loops or after an early return, so they run in the same order on every render. And call them only from React components or other hooks, not from ordinary functions. React relies on call order to know which state belongs to which hook.

Why the order matters. React does not know your hooks by name. It keeps a list per component and matches hooks by their position: first useState, second useState, first useEffect, and so on. If a hook is skipped on one render, every hook after it gets the wrong slot.

tsx
function Checkout({ isGuest }: { isGuest: boolean }) {
  const [email, setEmail] = useState('')            // slot 1
  if (!isGuest) {
    const [points, setPoints] = useState(0)          // (1) wrong: slot 2 only sometimes
  }
  const [address, setAddress] = useState('')        // slot 2 or 3?
  // ...
}
  1. A hook inside a condition. When isGuest changes, address would read the slot that used to belong to points. React detects this and throws "Rendered fewer hooks than expected".

The fix: always call the hook, and use the condition on the value:

tsx
const [points, setPoints] = useState(0)     // always called
const visiblePoints = isGuest ? null : points

Enforce it automatically with the eslint-plugin-react-hooks rules, which also check effect dependencies (question 13).

The built-in hooks you should know:

HookPurpose
useState, useReducerState (questions 12 and 19)
useEffect, useLayoutEffectSide effects after rendering (question 13)
useRefA mutable box that survives renders (question 16)
useMemo, useCallbackRemember a computed value or function (question 17)
useContextRead shared data from a provider (question 18)
useTransition, useDeferredValueKeep the UI responsive during heavy updates (question 27)
use, useActionState, useOptimistic, useEffectEventNewer React 19 hooks (question 22)

12. How does useState work, and why are state updates asynchronous? ​

The short answer

useState(initial) returns the current value and a setter. Calling the setter does not change the variable immediately; it schedules a re-render, and on that render useState returns the new value. Inside one event handler, React batches all state updates into a single re-render, so reading the state right after setting it still gives the old value. When the new value depends on the old one, pass a function, setCount((c) => c + 1), so each update uses the latest value.

The surprise interviewers test:

tsx
function AddButton() {
  const [qty, setQty] = useState(0)

  function addThree() {
    setQty(qty + 1)               // (1) qty is 0 here
    setQty(qty + 1)               // still 0
    setQty(qty + 1)               // still 0
    console.log(qty)              // (2) 0
  }
  // after the click, qty is 1, not 3
}
  1. qty is a constant for this render. Each call schedules "set to 0 + 1". Three times "set to 1" is still 1.
  2. The log shows the old value, because the variable belongs to the render that is already running. The new value appears in the next render.

The fix: updater functions.

tsx
function addThree() {
  setQty((q) => q + 1)            // (1)
  setQty((q) => q + 1)
  setQty((q) => q + 1)            // qty becomes 3
}
  1. React queues the functions and runs them in order, each receiving the result of the previous one.

Why updates are batched. If every setState rendered immediately, a handler that updates five pieces of state would render five times, and the screen could briefly show a half-updated state. Since React 18, updates are batched everywhere: in event handlers, timeouts, promises and native listeners.

Other details that matter:

DetailExample
Lazy initial stateuseState(() => loadDraftFromStorage()): the function runs only on the first render
Same value bails outsetQty(5) when it is already 5 usually skips the re-render, compared with Object.is
Objects must be replaced, not changedsetCart({ ...cart, items: [...cart.items, item] })
Changing an object in placecart.items.push(item); setCart(cart) does nothing: same reference, so React sees no change

The last row is the most common state bug. React compares references, so a changed-in-place object looks unchanged (question 45).

13. How does useEffect work, including dependencies and cleanup? ​

The short answer

useEffect(fn, deps) runs fn after React has updated the screen, to synchronise with something outside React, such as a subscription, a timer, a WebSocket or the document title. The dependency array controls when it re-runs: after every render with no array, once after mounting with [], or whenever a listed value changes. If fn returns a function, React calls that cleanup before running the effect again and when the component unmounts, so you can unsubscribe and cancel work.

① mounteffect: connect "general"② roomId changescleanup: disconnect "general"③ then effect againconnect "sales"④ unmountcleanup: disconnect "sales"
Every connect has its disconnect. ① After the first render, the effect runs. ② When a dependency changes, the previous cleanup runs first. ③ Then the effect runs with the new values. ④ When the component leaves the screen, the last cleanup runs.
tsx
function OrderUpdates({ orderId }: { orderId: string }) {
  const [status, setStatus] = useState('loading')

  useEffect(() => {
    const socket = new WebSocket(`wss://shop.example/orders/${orderId}`)     // (1)
    socket.onmessage = (e) => setStatus(JSON.parse(e.data).status)
    return () => socket.close()                                               // (2)
  }, [orderId])                                                               // (3)

  useEffect(() => {
    document.title = `Order ${orderId}: ${status}`                            // (4)
  }, [orderId, status])

  return <p>Status: {status}</p>
}
  1. Connect to something outside React, after the component is on screen.
  2. The cleanup closes the connection: before reconnecting for a new orderId, and when the component unmounts. Without it, every order the user views leaves one more socket open.
  3. Dependencies: re-run only when orderId changes.
  4. A second effect for a different concern. Split effects by what they synchronise, not by "everything that happens on mount".
Dependency arrayRuns
NoneAfter every render
[]After the first render only, cleanup on unmount
[a, b]After the first render, and whenever a or b changes, compared with Object.is

The dependency rule: list every value from the component that the effect reads, such as props, state and functions defined in the component. The lint rule does this for you. Leaving one out to "make it run less" causes stale values (question 21).

You might not need an effect. Effects are for talking to the outside world. They are not for computing values from props or state, which you do during render, or for responding to a user's click, which belongs in the click handler. A common anti-pattern is an effect that copies one state into another, which renders twice and can loop.

14. Why does my effect run twice in development? ​

The short answer

In development, React's StrictMode deliberately mounts every component, unmounts it, and mounts it again, so each effect runs, cleans up and runs again. It does this to prove your cleanup is correct: if the second run causes a problem, such as two open connections or a duplicated subscription, the same problem would appear in production whenever the component remounts. It never happens in production builds. The fix is a correct cleanup, not removing StrictMode.

A buggy effect that StrictMode exposes:

tsx
useEffect(() => {
  analytics.subscribe('cart-changed', track)      // no cleanup: two subscriptions in dev
}, [])

Fixed:

tsx
useEffect(() => {
  analytics.subscribe('cart-changed', track)
  return () => analytics.unsubscribe('cart-changed', track)
}, [])

What about data fetching that runs twice? Two requests in development are harmless if the effect ignores the stale response. A correct fetching effect cancels or ignores the first request:

tsx
useEffect(() => {
  const controller = new AbortController()
  fetch(`/api/orders/${orderId}`, { signal: controller.signal })
    .then((r) => r.json())
    .then(setOrder)
    .catch((err) => { if (err.name !== 'AbortError') setError(err) })
  return () => controller.abort()                  // cancels the first request
}, [orderId])

In real applications, use TanStack Query or a framework loader, which handle caching, de-duplication and cancellation for you (question 47).

When the effect must truly run once, such as logging "app started", run it outside React, at module level, or guard it with a module-level flag. Do not rely on the effect running once.

15. What is the difference between useEffect and useLayoutEffect? ​

The short answer

Both run after React has updated the DOM. useEffect runs after the browser has painted the screen, so it never delays what the user sees, and it is right for almost everything. useLayoutEffect runs after the DOM update but before the browser paints, blocking the paint until it finishes. Use it only when you must measure the layout and change it before the user sees a flicker, such as positioning a tooltip next to its button.

tsx
function Tooltip({ anchor, text }: { anchor: DOMRect; text: string }) {
  const ref = useRef<HTMLDivElement>(null)
  const [top, setTop] = useState(0)

  useLayoutEffect(() => {
    const height = ref.current!.getBoundingClientRect().height     // (1)
    setTop(anchor.top - height - 8)                                // (2)
  }, [anchor])

  return <div ref={ref} style={{ position: 'fixed', top }}>{text}</div>
}
  1. Measure the tooltip's real height, which is only known after it is in the DOM.
  2. Reposition before the browser paints. With useEffect, the user would see the tooltip at the wrong place for one frame, then jump.
useEffectuseLayoutEffect
RunsAfter paintBefore paint
Blocks the screen updateNoYes
Use forData, subscriptions, logging, most thingsMeasuring and adjusting layout
On the serverSkippedSkipped, with a warning in some setups

Start with useEffect, and switch only if you can see a flicker.

16. What is useRef used for? ​

The short answer

useRef(initial) gives you an object, { current: initial }, that stays the same object for the whole life of the component. Changing ref.current does not cause a re-render. It has two main uses: holding a reference to a DOM element, such as an input to focus, and keeping a mutable value between renders that should not trigger rendering, such as a timer ID, the previous value of a prop, or whether a request is still in flight.

tsx
function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
  const inputRef = useRef<HTMLInputElement>(null)                  // (1)
  const timerRef = useRef<number | undefined>(undefined)           // (2)
  const renders = useRef(0)
  renders.current += 1                                             // (3)

  useEffect(() => {
    inputRef.current?.focus()                                      // (4)
  }, [])

  function onChange(e: React.ChangeEvent<HTMLInputElement>) {
    window.clearTimeout(timerRef.current)
    const q = e.target.value
    timerRef.current = window.setTimeout(() => onSearch(q), 300)   // (5)
  }

  return <input ref={inputRef} onChange={onChange} placeholder="Search products" />
}
  1. A DOM ref: React sets inputRef.current to the input element after mounting.
  2. A value ref for the debounce timer ID (question 92).
  3. Changing it does not re-render, so this counter is safe. With useState, it would loop for ever.
  4. Using the DOM node: focus the box when the page opens.
  5. Store the new timer ID without rendering.
useStateuseRef
Changing it re-rendersYesNo
Value read during renderThe snapshot for that renderThe latest, always
Use forWhat the screen showsDOM nodes and behind-the-scenes values

Do not read or write refs during rendering for values that affect what is shown, because the screen will not update when they change. Refs are for event handlers and effects.

In React 19, a function component can receive ref as a normal prop, so forwardRef is no longer needed for new code.

17. What do useMemo and useCallback do, and when should you use them? ​

The short answer

useMemo(() => compute(a, b), [a, b]) remembers the result of a calculation and recomputes it only when its dependencies change. useCallback(fn, deps) remembers a function, so the same function object is returned until its dependencies change. Use them when a calculation is truly expensive, or when a stable reference matters: passing a value or callback to a child wrapped in React.memo, or to another hook's dependency array. Elsewhere they add complexity for no gain, and the React Compiler can now add them automatically.

tsx
function OrderList({ orders, onSelect }: { orders: Order[]; onSelect: (id: string) => void }) {
  const [query, setQuery] = useState('')
  const [sortBy, setSortBy] = useState<'date' | 'total'>('date')

  const visible = useMemo(                                          // (1)
    () => orders
      .filter((o) => o.customer.toLowerCase().includes(query.toLowerCase()))
      .toSorted((a, b) => (sortBy === 'total' ? b.total - a.total : b.date - a.date)),
    [orders, query, sortBy],
  )

  const handleSelect = useCallback((id: string) => {                 // (2)
    analytics.track('order-opened', { id })
    onSelect(id)
  }, [onSelect])

  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      {visible.map((o) => <OrderRow key={o.id} order={o} onSelect={handleSelect} />)}   {/* (3) */}
    </>
  )
}

const OrderRow = memo(function OrderRow(props: { order: Order; onSelect: (id: string) => void }) {
  return <li onClick={() => props.onSelect(props.order.id)}>{props.order.customer}</li>
})
  1. Filtering and sorting 5,000 orders runs only when the orders, the query or the sort changes, not on every unrelated render.
  2. A stable function. Without useCallback, a new handleSelect would be created on every render.
  3. Why the stable function matters here: OrderRow is wrapped in memo, which skips re-rendering when props are unchanged. A new function each time would count as a changed prop, and every row would re-render anyway (question 24).

When they are a waste:

CaseWhy it does not help
Cheap calculations, such as adding two numbersThe memo bookkeeping costs more than the work
Callbacks passed to plain DOM elements, <button onClick>DOM elements do not compare props
Children not wrapped in memoThey re-render anyway
Dependencies that change every renderThe cache never hits

useMemo is a performance hint, not a guarantee. React may throw away memoised values, so never rely on it for correctness, such as to keep one instance of an object alive. Use a ref or state for that.

The React Compiler analyses your components at build time and memoises values and callbacks automatically, which removes most hand-written useMemo and useCallback in new code (question 25).

18. How does useContext work, and what are its performance pitfalls? ​

The short answer

Context passes a value through the component tree without threading it through every level's props. You create it with createContext, provide a value with a provider component near the top, and read it anywhere below with useContext. Its pitfall: every component that reads a context re-renders whenever the provided value changes, so putting a large, often-changing object in one context makes many components re-render. Split contexts, memoise the value, or use a state library for frequently changing data.

tsx
type Theme = 'light' | 'dark'
const ThemeContext = createContext<{ theme: Theme; toggle: () => void } | null>(null)   // (1)

function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useState<Theme>('light')
  const value = useMemo(                                                               // (2)
    () => ({ theme, toggle: () => setTheme((t) => (t === 'light' ? 'dark' : 'light')) }),
    [theme],
  )
  return <ThemeContext value={value}>{children}</ThemeContext>                          // (3)
}

function useTheme() {                                                                   // (4)
  const ctx = useContext(ThemeContext)
  if (!ctx) throw new Error('useTheme must be used inside <ThemeProvider>')
  return ctx
}

function ThemeToggle() {
  const { theme, toggle } = useTheme()
  return <button onClick={toggle}>{theme === 'light' ? '🌙' : '☀️'}</button>
}
  1. Create the context, with null as the value when there is no provider.
  2. Memoise the value object. Without it, a new object is created on every render of the provider, and every consumer re-renders even when the theme did not change.
  3. Provide it. In React 19 the context itself can be used as the provider; older code writes <ThemeContext.Provider value={value}>.
  4. A small custom hook gives a clear error when someone forgets the provider (question 20).

Good uses of context: values that change rarely and are needed widely, such as the theme, the current user, the locale, feature flags and dependency injection of services.

Poor uses: fast-changing data such as a text input's value, a mouse position, or a large shared store, because every consumer re-renders on every change. For that, use Zustand or Redux, which let each component subscribe to just the slice it needs (question 40).

19. When should you use useReducer instead of useState? ​

The short answer

Use useReducer when several pieces of state change together, when the next state depends on the previous one in complex ways, or when many different events update the same state. You write a pure reducer function, (state, action) => newState, that handles every kind of change in one place, and components just dispatch actions describing what happened. It makes complex updates predictable and easy to read, and is the same pattern Redux uses.

tsx
type CartState = { items: { sku: string; qty: number }[]; coupon: string | null }
type CartAction =
  | { type: 'added'; sku: string }
  | { type: 'removed'; sku: string }
  | { type: 'coupon-applied'; code: string }
  | { type: 'cleared' }

function cartReducer(state: CartState, action: CartAction): CartState {     // (1)
  switch (action.type) {
    case 'added': {
      const existing = state.items.find((i) => i.sku === action.sku)
      const items = existing
        ? state.items.map((i) => (i.sku === action.sku ? { ...i, qty: i.qty + 1 } : i))
        : [...state.items, { sku: action.sku, qty: 1 }]
      return { ...state, items }                                              // (2)
    }
    case 'removed':
      return { ...state, items: state.items.filter((i) => i.sku !== action.sku) }
    case 'coupon-applied':
      return { ...state, coupon: action.code }
    case 'cleared':
      return { items: [], coupon: null }
  }
}

function Cart() {
  const [cart, dispatch] = useReducer(cartReducer, { items: [], coupon: null })
  return <button onClick={() => dispatch({ type: 'added', sku: 'tea' })}>Add tea</button>   // (3)
}
  1. All the rules for changing the cart live in one pure function.
  2. Return a new object; never change state in place.
  3. Components describe what happened, not how to update the state.
useStateuseReducer
Best forOne or a few independent valuesRelated values changed by many events
Update logic livesIn each handlerIn one reducer
Readability as it growsGets scatteredStays in one place

A typed discriminated union for actions means TypeScript checks that each action has the right fields, and the switch can be made exhaustive (question 85).

20. What is a custom hook? ​

The short answer

A custom hook is your own function, whose name starts with use, that calls other hooks to package up reusable stateful logic, such as fetching data, reading local storage or tracking the window size. Each component that calls it gets its own independent copy of the state; hooks share logic, not data. It is the main way to reuse behaviour in modern React, replacing higher-order components and render props.

tsx
function useLocalStorage<T>(key: string, initial: T) {
  const [value, setValue] = useState<T>(() => {                    // (1)
    try {
      const stored = localStorage.getItem(key)
      return stored ? (JSON.parse(stored) as T) : initial
    } catch {
      return initial                                               // (2)
    }
  })

  useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(value)) } catch { /* storage full or blocked */ }
  }, [key, value])                                                 // (3)

  return [value, setValue] as const                                // (4)
}

function NewsletterBanner() {
  const [dismissed, setDismissed] = useLocalStorage('banner-dismissed', false)
  if (dismissed) return null
  return <aside>Get 10% off <button onClick={() => setDismissed(true)}>×</button></aside>
}
  1. Lazy initial state: read storage only once, on the first render.
  2. Storage can be blocked, in private windows for example, so fall back safely.
  3. Save whenever the value changes.
  4. Return a tuple, like useState, so callers can name the parts.

The "use" prefix matters. It tells React's lint rules that the rules of hooks apply inside (question 11). A function that calls no hooks should not start with use.

Common custom hooks teams write: useDebouncedValue, useMediaQuery, useOnClickOutside, useCurrentUser, and thin wrappers around TanStack Query calls, such as useOrders().

21. What is a stale closure in React, and how do you fix it? ​

The short answer

Every render has its own props and state, and functions created during that render close over those exact values. A stale closure is a function from an older render, such as a timer callback or an effect without the right dependencies, that keeps reading the old values after the state has moved on. Fix it by listing the value in the effect's dependencies, using a functional update such as setCount((c) => c + 1), keeping the latest value in a ref, or using useEffectEvent in React 19.2.

The classic bug:

tsx
function SessionTimer() {
  const [seconds, setSeconds] = useState(0)

  useEffect(() => {
    const id = setInterval(() => {
      setSeconds(seconds + 1)            // (1) always 0 + 1
    }, 1000)
    return () => clearInterval(id)
  }, [])                                 // (2)

  return <p>{seconds}s</p>               // shows 1, then stays at 1
}
  1. The interval callback was created in the first render, where seconds is 0, and it keeps that closure for ever (question 11).
  2. The empty dependency array means the effect never re-runs to create a fresh callback.
render 1seconds = 0render 2seconds = 1render 3seconds = 1interval callbacksets 0 + 1, every secondstill sees render 1
A photo from the first render. Each render is a snapshot. The interval callback was made in render 1, so it keeps reading that snapshot's value, whatever later renders hold.

Fixes, in order of preference:

tsx
// 1. Functional update: no need to read the current value at all
setSeconds((s) => s + 1)

// 2. Add the value to the dependencies: the effect restarts with fresh values
useEffect(() => {
  const id = setInterval(() => setSeconds(seconds + 1), 1000)
  return () => clearInterval(id)
}, [seconds])

// 3. A ref holding the latest value, read inside the long-lived callback
const latestCart = useRef(cart)
latestCart.current = cart
useEffect(() => {
  const id = setInterval(() => autosave(latestCart.current), 30_000)
  return () => clearInterval(id)
}, [])

React 19.2's useEffectEvent formalises fix 3: it wraps a function so that it always sees the latest props and state, but does not count as a dependency of the effect (question 22).

Stale closures also appear in event handlers passed to long-lived subscriptions, such as a WebSocket message handler registered once, and in useCallback with missing dependencies. The lint rule for hook dependencies catches most of them.

22. What are the newer React 19 hooks such as use, useActionState, useOptimistic and useEffectEvent? ​

The short answer

React 19 added hooks for common patterns that used to need boilerplate. use(promise) reads a promise's value during render, suspending until it resolves, and use(context) reads context, even inside conditions. useActionState manages a form action's pending state, result and errors. useOptimistic shows an expected result immediately while a request is in flight. React 19.2 added useEffectEvent, for logic inside an effect that should always see the latest values without re-running the effect.

useActionState and useOptimistic, for a newsletter form:

tsx
async function subscribeAction(prev: { error?: string }, formData: FormData) {
  const email = String(formData.get('email'))
  const res = await fetch('/api/subscribe', { method: 'POST', body: JSON.stringify({ email }) })
  return res.ok ? {} : { error: 'Could not subscribe, please try again' }
}

function Newsletter() {
  const [state, formAction, isPending] = useActionState(subscribeAction, {})   // (1)
  return (
    <form action={formAction}>                                                   {/* (2) */}
      <input name="email" type="email" required />
      <button disabled={isPending}>{isPending ? 'Subscribing…' : 'Subscribe'}</button>
      {state.error && <p role="alert">{state.error}</p>}
    </form>
  )
}

function LikeButton({ liked, onToggle }: { liked: boolean; onToggle: () => Promise<void> }) {
  const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked)            // (3)
  return (
    <form action={async () => { setOptimisticLiked(!optimisticLiked); await onToggle() }}>
      <button>{optimisticLiked ? '♥' : '♡'}</button>
    </form>
  )
}
  1. useActionState returns the last result, an action to give the form, and whether it is running.
  2. Forms accept functions as action in React 19. React handles the submission and the pending state.
  3. useOptimistic shows the new state at once. When the action finishes, React switches back to the real liked value, so a failure automatically rolls the display back.

useEffectEvent, logging with the latest theme without reconnecting:

tsx
function ChatRoom({ roomId, theme }: { roomId: string; theme: string }) {
  const onConnected = useEffectEvent(() => showToast(`Connected to ${roomId}`, theme))  // (1)
  useEffect(() => {
    const conn = connect(roomId)
    conn.on('connected', () => onConnected())
    return () => conn.disconnect()
  }, [roomId])                                                                         // (2)
}
  1. An effect event always reads the latest theme.
  2. The effect depends only on roomId, so changing the theme does not reconnect the chat.
HookReplaces
useReading a promise in an effect plus loading state; useContext in conditions
useActionStateuseState for pending, error and result around a submit handler
useOptimisticHand-written optimistic state with manual rollback
useFormStatusProp drilling a "pending" flag into a submit button
useEffectEventThe "latest value in a ref" workaround (question 21)

In practice, data fetching in client apps is still usually done with TanStack Query (question 47); use with promises shines with frameworks that create the promise on the server.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
React, Vite & Next.js
React
State and data
Vite
Next.js
Other topics
Nothing picked yet