JAVASCRIPT

Access Previous State or Prop Value in React

Learn to create a `usePrevious` React hook for easily accessing the previous value of any state or prop, useful for comparing current and past data in effects.

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 provides a simple way to store and retrieve the value of a variable (state or prop) from the previous render cycle. It uses a `useRef` to maintain the value across renders and updates it inside a `useEffect` after the component has rendered, ensuring that `ref.current` always holds the value from the immediately preceding render. This is handy for comparing changes or implementing specific logic based on value transitions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs