CodeBlanks Logo Icon CodeBlanks

usePrevious

Learn the usePrevious custom hook.

What is usePrevious?

usePrevious is a custom hook that keeps the value from the previous render. It is built with one useRef and one useEffect. It returns the previous value to the calling component on each render.

Common use: show whether a number grew or shrank, or compare old and new values. You write const prev = usePrevious(count); on the first render prev is undefined, on the second render you get the previous count. This hook is handy on dashboards.

How usePrevious works

usePrevious is built from two pieces. A useRef holds the previous value; a useEffect updates that ref after render. Inside the effect you assign ref.current = value; but since the effect runs after render, this assignment is visible on the next render.

So the hook first returns ref.current (the old value), then the effect runs and updates the ref to the new value. This order gives you the value from the previous render. Since ref.current does not trigger a re-render, no infinite loop occurs.

Practice Write usePrevious

Write the usePrevious custom hook. Create ref with useRef (initial value undefined). Inside useEffect assign ref.current = value; the dependency array is [value]. The hook returns ref.current.

Starter code

App.js
// Import useRef and useEffect

// Write the usePrevious custom hook
// Create ref with useRef
// Inside useEffect assign the new value to ref.current; array [value]
// Return ref.current

Sample solution

App.js
import { useEffect, useRef } from "react";

function usePrevious(value) {
  const ref = useRef(undefined);
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does usePrevious return on the first render?

App.js
const prev = usePrevious(count);
  • The current value
  • undefined Correct answer
  • Throws an error
  • Zero

Explanation: On the first render there is no previous value.

2 Write the useEffect dependency

Question
useEffect(() => {
  ref.current = value;
}, ____);
Answer
useEffect(() => {
  ref.current = value;
}, [value]);

Explanation: The effect re-runs when value changes.

3 Match the concept to its role

Term Meaning
useRef Holds old value
useEffect Updates the ref
ref.current Returned value
undefined First-render value

All lessons in Intermediate