JAVASCRIPT
React `usePrevious` Hook to Access Previous State or Prop Values
Discover how to easily get the previous value of any state or prop in React components using the `usePrevious` custom hook, essential for diffing updates.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance field on a class
const ref = useRef();
// Store current value in ref on *every* render
useEffect(() => {
ref.current = value;
});
// Return previous value (happens before update in useEffect)
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 access the value of a prop or state from the previous render. It uses a `useRef` to store the current value. In a `useEffect` hook, the `ref.current` is updated with the latest `value` after every render, but `useRef` returns the value it held *before* that render, effectively giving you the 'previous' value.