React Hooks useRef and useMemo 2 — Questions and Answers
Question 1: What is a common use case for useRef that does NOT involve DOM access?
- Storing the previous value of a prop or state (Correct answer)
- Creating global state
- Replacing useState for all values
- Generating unique IDs in JSX
Correct answer: Storing the previous value of a prop or state
Storing a previous value in a ref lets you compare current and previous values without triggering re-renders.
Question 2: What hook is semantically related to useMemo but applies to functions instead of values?
- useCallback (Correct answer)
- useEffect
- useState
- useRef
Correct answer: useCallback
useCallback memoizes a function reference so it only changes when its dependencies change, analogous to useMemo for values.
Question 3: Why is over-using useMemo considered an anti-pattern?
- It causes hydration errors
- Memoization itself has overhead; the benefit only justifies complex computations (Correct answer)
- It prevents state updates
- React ignores it in production
Correct answer: Memoization itself has overhead; the benefit only justifies complex computations
Every useMemo call has bookkeeping cost, so memoizing simple or fast operations can be slower than recomputing.
Question 4: How can useRef help avoid stale closures in event handlers?
- By storing the latest value in ref.current so the handler always reads up-to-date data (Correct answer)
- By triggering re-renders with new closures
- By storing the handler in state
- By replacing useEffect
Correct answer: By storing the latest value in ref.current so the handler always reads up-to-date data
Storing the current value in a ref lets an event handler read the latest value without being recreated on every render.
Question 5: Will useMemo run during server-side rendering (SSR)?
- No, it is browser-only
- Yes, it runs on both server and client (Correct answer)
- Only in Next.js
- Only if StrictMode is disabled
Correct answer: Yes, it runs on both server and client
useMemo runs during SSR just like on the client, though React does not guarantee caching between server requests.
Question 6: What does React do with the value returned by useMemo when the component unmounts?
- It stores it in localStorage
- It is garbage collected along with the component (Correct answer)
- It is transferred to the parent component
- It persists across future renders
Correct answer: It is garbage collected along with the component
The memoized value is part of the component's fiber and is garbage collected when the component unmounts.
What is a common use case for useRef that does NOT involve DOM access?