Frontend Interview Questions

React Hooks: Rules of Hooks and useEffect Internals

Why must hooks be called at the top level? Explain useEffect's lifecycle.

Why Interviewers Ask This

Hooks fluency is core to any React role. Interviewers test whether you've hit the classic stale-closure bugs.

How to Answer

  1. 1

    Hooks are stored per component in an ordered list. React identifies each hook by call order. Conditional hooks break the index → state misalignment.

  2. 2

    useEffect runs after commit: mount first (run effect), update (cleanup previous then run new), unmount (cleanup).

  3. 3

    Dependency array: React shallow-compares; reference identity matters, so an object literal in deps triggers every render.

  4. 4

    Stale closure: an effect captures state at render time; forgetting a dep means it keeps seeing old state. Use ESLint exhaustive-deps plugin.

  5. 5

    useMemo caches a computed value; useCallback caches a function reference. Both prevent downstream re-renders that depend on reference equality.

Sample Answer

React stores hooks in an array per component, identified by call order — `useState` at position 0, `useEffect` at position 1, etc. If you wrap a hook in an if, call order diverges between renders and state binds to the wrong slot. That's why the top-level rule exists. useEffect runs after commit: mount runs the effect, updates run cleanup-then-effect, unmount runs only cleanup. Classic bug: stale closure — effect captures state at render time, so an interval or subscription sees old values forever unless you list every dep. The exhaustive-deps ESLint rule catches this; I never silence it without a comment explaining why. useMemo for expensive computation, useCallback for stable function references passed to memoized children — overusing both hurts more than it helps because memoization itself costs.

Pro Tips

  • If a dep needs to be stable, wrap its producer in useCallback/useMemo at the source.

  • useRef is the escape hatch for "I need this value but don't want renders".

  • HireMe AI (即答侠) drills 5 stale-closure scenarios so the pattern is instantly recognizable.

Frequently Asked Questions

Can I conditionally call a hook inside a try/catch?

Only if execution always reaches the same hooks in the same order. Throws that skip later hooks break the invariant.

useEffect vs useLayoutEffect?

useEffect runs after paint (async, non-blocking). useLayoutEffect runs synchronously after DOM mutations but before paint — use when you need to measure/mutate before the user sees anything.

Worried About Going Blank in Your Interview?

HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.

Try HireMe AI Free