usePrevious
- React course
- Intermediate
- Lesson 3/80
- 4 min
Write a usePrevious hook that stores the previous value.
usePrevious
usePrevious remembers the value from the previous render. React state holds only the current value; the previous one isn't directly accessible.
The fix: hold a memory with useRef, update it after each render with useEffect. const ref = useRef(value); useEffect(() => { ref.current = value; }); return ref.current;
Tip: useEffect's dependency array should be [value]. So ref is updated only when value changes. This hook is also useful in animations to compare old/new values.
useEffect order
useEffect runs after the render is painted. So the assignment ref.current = value happens after the component is drawn. That's why the returned ref.current is still the old value; the new one appears in the next render.
That's why the hook is named "usePrevious". It reads the previous value during render, then prepares for the next render after.
This ordering can be confusing at first but it's central to React's render model. Side effects always run after paint.
Practice Write usePrevious
Complete the skeleton. Write a usePrevious(value) hook. Create ref with useRef(value). Inside useEffect, assign ref.current = value; the dependency array is [value]. Return ref.current. Export the hook.
Starter code
import { useRef, useEffect } from "react";
// Write the usePrevious hook hereSample solution
import { useRef, useEffect } from "react";
function usePrevious(value) {
const ref = useRef(value);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
export default usePrevious;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which hooks does usePrevious use?
- useMemo and useCallback
- useState and useContext
- useReducer and useRef
- useRef and useEffect Correct answer
Explanation: usePrevious uses useRef and useEffect.
2 Access
The previous value is accessed via ____.
The previous value is accessed via ref.current.
Explanation: Accessed via ref.current.
3 Match the usePrevious steps
| Term | Meaning |
|---|---|
useRef(value) |
Initial |
useEffect |
Side effect |
ref.current = value |
Update |
return ref.current |
Old value |