← Back to all snippets
JAVASCRIPT

Custom usePrevious Hook for Storing Past State/Props

A simple and powerful React custom hook that tracks and returns the previous value of any state or prop, ideal for comparing values across re-renders.

import { useRef, useEffect } from 'react';

const usePrevious = (value) => {
  const ref = useRef();

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

  return ref.current; // Return the previous value (before current render)
};

export default usePrevious;

// How to use:
// import usePrevious from './usePrevious';
// function Counter() {
//   const [count, setCount] = useState(0);
//   const prevCount = usePrevious(count);
//   return (
//     <div>
//       <p>Current: {count}, Previous: {prevCount}</p>
//       <button onClick={() => setCount(count + 1)}>Increment</button>
//     </div>
//   );
// }
How it works: The `usePrevious` hook provides a convenient way to access the value of a state or prop from the previous render cycle. It uses a `useRef` to persist the value across renders without causing re-renders itself. Inside a `useEffect` hook, the current `value` is stored in `ref.current` *after* the component has rendered. Therefore, on the next render, `ref.current` will hold the value from the *previous* render, which is then returned by the hook. This is particularly useful for comparing current and past values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs