JAVASCRIPT

Capture Previous State or Prop Value with usePrevious Hook

Learn to create a custom React usePrevious hook to easily access the previous value of any state or prop, essential for comparing changes across renders.

import { useRef, useEffect } from 'react';

const 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: This custom `usePrevious` hook utilizes the `useRef` hook to store the value from the previous render. In the `useEffect` callback, which runs *after* the render, `ref.current` is updated with the current `value`. The hook then returns `ref.current`, giving you access to the value *before* the most recent update, making it perfect for comparing changes over time within a component's lifecycle.

Need help integrating this into your project?

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

Hire DigitalCodeLabs