JAVASCRIPT

Tracking Previous State or Prop Values with usePrevious Hook

A custom React hook `usePrevious` that stores and returns the previous value of any prop or state variable, useful for comparing current and past values.

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>
//       <p>Current: {count}, Previous: {prevCount}</p>
//       <button onClick={() => setCount(count + 1)}>Increment</button>
//     </div>
//   );
// }
How it works: The `usePrevious` hook leverages the `useRef` hook to store a mutable value that persists across renders without causing re-renders. Inside a `useEffect` hook, which runs after every render where the `value` changes, `ref.current` is updated to the current `value`. The hook then returns the `ref.current` from the *previous* render cycle, effectively giving you the prior value of the passed variable.

Need help integrating this into your project?

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

Hire DigitalCodeLabs