JAVASCRIPT

React Hook: usePrevious for Tracking Previous State or Props

A custom React hook to efficiently store and retrieve the previous value of any state, prop, or variable, enabling powerful "diffing" and change detection logic in your components.

import { useRef, useEffect } from 'react';

function usePrevious(value) {
  // The ref object is a generic container whose current property is mutable and can hold any value,
  // similar to an instance field on a class.
  const ref = useRef();

  // Store current value in ref on each render
  useEffect(() => {
    ref.current = value;
  }, [value]); // Only re-run if value changes

  // Return the previous value (happens before the useEffect updates ref.current)
  return ref.current;
}
How it works: The `usePrevious` hook leverages React's `useRef` to maintain a mutable reference to the value from the previous render. In the `useEffect` callback, the current `value` is stored in `ref.current`. This `useEffect` runs *after* the component renders, meaning that on the subsequent render, `ref.current` will hold the value that was current during the *previous* render cycle. The hook then returns this `ref.current` value, effectively providing the 'previous' state or prop.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs