JAVASCRIPT
Track Previous State or Prop Values with usePrevious in React
Implement a usePrevious custom hook in React to easily access the previous value of any state or prop, useful for comparing changes and conditional logic.
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}</p>
// <p>Previous: {prevCount !== undefined ? prevCount : 'N/A'}</p>
// <button onClick={() => setCount(count + 1)}>Increment</button>
// </div>
// );
// }
How it works: This `usePrevious` custom hook provides a way to get the value of a state or prop from the previous render. It leverages `useRef` to store the value in a mutable `ref` object. Inside a `useEffect` hook, the `ref.current` is updated with the current `value` *after* the render, ensuring that `ref.current` always holds the value from the *previous* render cycle when the component re-renders. This is useful for comparing current and past values.