JAVASCRIPT

React usePrevious Hook to Track Previous State or Prop Values

Create a usePrevious custom hook in React to store and retrieve the previous value of any state or prop, useful for comparing current and past data.

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;
}

// Usage example:
// function Counter() {
//   const [count, setCount] = useState(0);
//   const prevCount = usePrevious(count);
//
//   return (
//     <div>
//       <p>Current: {count}</p>
//       <p>Previous: {prevCount !== undefined ? prevCount : 'N/A'}</p>
//       <button onClick={() => setCount(count + 1)}>Increment</button>
//     </div>
//   );
// }
How it works: The `usePrevious` hook allows you to easily get the previous value of a prop or state. It uses a `useRef` to store the value from the *last* render cycle. Inside `useEffect`, the current `value` is assigned to `ref.current` *after* the render, ensuring that `ref.current` always holds the value from the previous render when accessed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs