JAVASCRIPT

Access Previous State or Prop Values with usePrevious React Hook

Learn to create a simple yet powerful React hook to keep track of the previous value of any state or prop, useful for comparing changes in your components.

import { useRef, useEffect } from 'react';

function usePrevious(value) {
  const ref = useRef();

  useEffect(() => {
    ref.current = value;
  }, [value]);

  return ref.current;
}

// How to use it:
// 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: The `usePrevious` hook allows you to easily access the value of a prop or state from the previous render cycle. It leverages the `useRef` hook to store the `value` passed into it. The `useEffect` hook updates the `ref.current` to the current `value` *after* every render. This ensures that when the component renders, `ref.current` still holds the value from the *previous* render, making it available for comparison or other logic before it's updated for the next render.

Need help integrating this into your project?

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

Hire DigitalCodeLabs