React
useRef and computation
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.
Exercise 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.
Show example 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;
Test yourself
-
What happens when useRef is updated?
- The component is not rendered
- The component is rendered
- State is reset
- Throws an error
Show answer
The component is not rendered — Updating useRef does not re-render the component.
-
Reading ref
const lastRef = useRef(null);
if (lastRef.____ !== value) {
lastRef.current = value;
compute();
}
Show answer
const lastRef = useRef(null);
if (lastRef.current !== value) {
lastRef.current = value;
compute();
}
-
useRef and computation: match the terms
- useRef
- Holds a value
- current
- Ref property
- no re-render
- Ref update
- cache
- Skipping a computation
Next lesson: Measuring