useRef and computation
- React course
- Intermediate
- Lesson 65/80
- 4 min
Learn to keep a value with useRef without triggering renders.
useRef and computation
useRef holds a variable across renders. Unlike state, updating a ref does not re-render the component. This is useful for caching computation results.
For example, you can store a function's previous result in a ref; when the same input comes again, read from the ref instead of recomputing. This is similar to useMemo but provides manual control.
The ref's current property is mutable; but this happens without React knowing, so it does not trigger a render.
Computation cache
Caching computation with a ref is common. You store a heavy computation's result in ref.current; when the same input comes again, skip the computation and read from the ref. This avoids unnecessary work.
Example: if a filter function processes thousands of items, storing the last input and result in a ref makes sense. If the input has not changed, return the same result.
Using a ref instead of state: the cache update should not trigger a render; only a real result change should render.
Practice Cache with ref
Complete the skeleton below. Write a UseCache component; get cacheRef with useRef(null), check the previous value with cacheRef.current, if different set cacheRef.current = value and compute. Export it.
Starter code
import { useRef } from "react";
// Write the UseCache component hereSample solution
import { useRef } from "react";
function UseCache({ value }) {
const cacheRef = useRef(null);
if (cacheRef.current !== value) {
cacheRef.current = value;
compute(value);
}
return <p>{value}</p>;
}
export default UseCache;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when useRef is updated?
- The component is not rendered Correct answer
- The component is rendered
- State is reset
- Throws an error
Explanation: Updating useRef does not re-render the component.
2 Reading ref
const lastRef = useRef(null);
if (lastRef.____ !== value) {
lastRef.current = value;
compute();
}
const lastRef = useRef(null);
if (lastRef.current !== value) {
lastRef.current = value;
compute();
}
Explanation: ref.current accesses the stored value.
3 useRef and computation: match the terms
| Term | Meaning |
|---|---|
useRef |
Holds a value |
current |
Ref property |
no re-render |
Ref update |
cache |
Skipping a computation |