JAVASCRIPT

usePrevious Hook for Tracking Previous State/Prop Values

Learn to build a simple `usePrevious` hook in React to easily access the prior value of any state or prop, essential for comparing current and past data in `useEffect` and other hooks.

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}, Previous: {prevCount !== undefined ? prevCount : 'N/A'}</p>
//       <button onClick={() => setCount(count + 1)}>Increment</button>
//     </div>
//   );
// }
How it works: The `usePrevious` hook allows you to get the value of a prop or state from the previous render cycle. It leverages the `useRef` hook to store the current value, which persists across renders without causing re-renders itself. In the `useEffect` callback, the `ref.current` is updated *after* the render, ensuring that on the *next* render, `ref.current` holds the value from the *previous* render. This is invaluable for comparing current and prior values in effects or callbacks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs