JAVASCRIPT

How to use usePrevious hook to get the previous state or prop

Learn to create a custom React hook, usePrevious, to store and retrieve the prior value of any state or prop, essential for comparing changes.

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>
//       <h1>Current: {count}, Previous: {prevCount}</h1>
//       <button onClick={() => setCount(count + 1)}>Increment</button>
//     </div>
//   );
// }
How it works: The usePrevious hook utilizes useRef to persist a value across renders without causing re-renders. The useEffect hook updates the ref.current value after every render, ensuring it always holds the "previous" value before the current render's state or prop change, making it useful for comparing current and past values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs