javascript / intermediate
Snippet
Tracking Previous Values with Custom Hooks
Since useEffect runs after the render is committed, you can use a ref to store the 'current' value during the effect. This allows you to access the value from the previous render cycle during the next one.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
function usePrevious(value) {const ref = useRef();useEffect(() => {ref.current = value;}, [value]);return ref.current;}// In a component:const prevCount = usePrevious(count);
react
Breakdown
1
const ref = useRef();
Creates a persistent object that stays the same across renders.
2
ref.current = value;
Updates the ref with the new value after the render has finished.
3
return ref.current;
Returns the value assigned during the *previous* effect run.