JAVASCRIPT

Accessing Previous Prop or State Values with usePrevious Hook

Implement a custom React hook to easily access the previous value of any prop or state variable, useful for comparing changes in `useEffect` or other logic.

import { useRef, useEffect } from 'react';

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

  useEffect(() => {
    ref.current = value;
  }, [value]); // Only re-run if value changes

  return ref.current;
}

// Example Usage:
// function Counter() {
//   const [count, setCount] = useState(0);
//   const prevCount = usePrevious(count);

//   useEffect(() => {
//     console.log(`Current count: ${count}, Previous count: ${prevCount}`);
//   }, [count, prevCount]); // Log whenever count or prevCount changes

//   return (
//     <div>
//       <p>Count: {count}</p>
//       <p>Previous Count: {prevCount !== undefined ? prevCount : 'N/A'}</p>
//       <button onClick={() => setCount(count + 1)}>Increment</button>
//     </div>
//   );
// }
How it works: The `usePrevious` hook provides a simple way to get the value of a state or prop from the previous render. It uses a `useRef` to store the value from the *last* render. The `useEffect` hook updates this `ref.current` *after* the render, so on the *next* render, `ref.current` will hold the value from the *previous* render. This is particularly useful for comparing current and past values within other hooks or logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs