← Back to all snippets
JAVASCRIPT

Track Previous Values of Props or State in React

Get access to the previous value of any prop or state in a React component, useful for comparing current and past states or triggering effects based on changes.

import { useRef, useEffect } from 'react';

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = 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: The `usePrevious` hook provides a simple way to access the value of a prop or state from the previous render cycle. It uses a `useRef` to store the value. In the `useEffect` hook, which runs *after* every render, the `ref.current` is updated to the current `value`. Before this update, `ref.current` holds the value from the *previous* render, allowing you to compare it with the current `value` in your component's logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs