JAVASCRIPT

Tracking Previous State or Prop Values with usePrevious

Discover how to create a React `usePrevious` hook to easily store and access the previous value of any state or prop, enabling advanced change detection logic.

import { useRef, useEffect } from 'react';

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

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

  return ref.current;
}

// Example Usage:
// function Counter() {
//   const [count, setCount] = useState(0);
//   const prevCount = usePrevious(count);

//   return (
//     <div>
//       <p>Current: {count}</p>
//       <p>Previous: {prevCount}</p>
//       <button onClick={() => setCount(count + 1)}>Increment</button>
//     </div>
//   );
// }
How it works: The `usePrevious` hook provides a simple way to access the value of a state or prop from the previous render cycle. It uses a `useRef` to store the value. In the `useEffect` hook, the `ref.current` is updated to the `current value` after the render. On the next render, `ref.current` will still hold the value from the *previous* render. This is invaluable for comparing current and previous values to trigger effects or logic only when specific changes occur.

Need help integrating this into your project?

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

Hire DigitalCodeLabs