JAVASCRIPT

Track Previous State or Prop Value with usePrevious Hook

Create a simple custom React hook to easily access the previous value of a prop or state variable, valuable for comparisons and conditional logic.

import { useRef, useEffect } from 'react';

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

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

  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 utilizes `useRef` and `useEffect` to store the value from the previous render. On each render, `useEffect` updates the ref to the *current* value, but `ref.current` will still hold the value from the *previous* render until the effect runs. This allows components to easily access the prior state or prop, which is useful for comparing changes, animating transitions, or applying conditional logic based on value shifts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs