Hooks · Quick recall Q&A

2 min read
Mid-level3 min read
Rapid overview

Quick recall Q&A

Q: When should I use useCallback vs useMemo?

Use useCallback to memoize functions, useMemo to memoize values. useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

Q: What's the difference between useEffect and useLayoutEffect?

useEffect runs after paint (asynchronous), useLayoutEffect runs before paint (synchronous). Use useLayoutEffect when you need to measure/mutate DOM before browser paints.

Q: When should I use useReducer instead of useState?

Use useReducer when you have complex state logic with multiple sub-values, when next state depends on previous state, or when you want to optimize performance by passing dispatch down instead of callbacks.

Q: How do I handle async operations in useEffect?

Create an async function inside the effect and call it, or use .then(). Never make the effect callback itself async. Always handle cleanup for race conditions.

Q: What causes infinite loops in useEffect?

Missing dependency array runs effect after every render. Including objects/arrays created during render as dependencies causes new references every render. Use useMemo or move object creation inside the effect.

Q: When should I create a custom hook?

When you have reusable stateful logic used in multiple components, complex logic that clutters components, or when you want to encapsulate related hooks together.

Q: Is it okay to call hooks in loops?

No, hooks must be called in the same order every render. Dynamic hook calls break React's internal tracking. Create separate components instead.

Q: How do I clean up subscriptions in useEffect?

Return a cleanup function from the effect. It runs before the effect re-runs and when component unmounts.

Q: What's the purpose of useRef?

Store mutable values that don't trigger re-renders when changed, access DOM elements, keep instance variables between renders, and track previous values.

Q: How do I optimize re-renders with hooks?

Use React.memo for components, useCallback for functions, useMemo for expensive calculations, split state to prevent unnecessary updates, and lift state only when needed.

See also