React Hooks useRef and useMemo 1 — Questions and Answers
Question 1: What does useRef return?
- A state value and setter
- A mutable ref object with a .current property (Correct answer)
- A memoized value
- A DOM element directly
Correct answer: A mutable ref object with a .current property
useRef returns a plain JavaScript object { current: initialValue } that persists for the full lifetime of the component.
Question 2: Does mutating a ref's .current property cause a re-render?
- Yes, always
- No, mutations to ref.current do not trigger re-renders (Correct answer)
- Only if the ref is connected to a DOM element
- Yes, but only in StrictMode
Correct answer: No, mutations to ref.current do not trigger re-renders
Refs are outside React's state system, so changing .current does not notify React or trigger a re-render.
Question 3: How do you attach a ref to a DOM element?
- Pass it as a prop called innerRef
- Pass it as the ref prop on the JSX element (Correct answer)
- Call useRef(element)
- Assign it in useEffect
Correct answer: Pass it as the ref prop on the JSX element
React automatically sets ref.current to the DOM node when you pass the ref object to the ref prop.
Question 4: What is useMemo used for?
- Storing DOM references
- Memoizing expensive computed values between renders (Correct answer)
- Triggering side effects
- Managing async state
Correct answer: Memoizing expensive computed values between renders
useMemo caches the result of a computation and only re-runs it when specified dependencies change.
Question 5: What are the two arguments to useMemo?
- A value and a default
- A factory function and a dependency array (Correct answer)
- A ref and a callback
- An initial value and a reducer
Correct answer: A factory function and a dependency array
useMemo takes a factory function (returning the value to memoize) and a dependency array.
Question 6: When does useMemo recompute its value?
- On every render
- Never after the first render
- When one or more items in the dependency array change (Correct answer)
- When the parent re-renders only
Correct answer: When one or more items in the dependency array change
useMemo re-runs the factory function only when a dependency value changes, returning the cached result otherwise.
What does useRef return?