JAVASCRIPT
Track Previous Value with `usePrevious` React Hook
Learn to create a custom React hook, `usePrevious`, to easily access the prior value of any state or prop, essential for comparisons and conditional logic in your components.
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>
// <h1>Current: {count}, Previous: {prevCount}</h1>
// <button onClick={() => setCount(count + 1)}>Increment</button>
// </div>
// );
// }
How it works: The `usePrevious` hook utilizes `useRef` to store the previous value. Inside a `useEffect` hook, `ref.current` is updated with the current `value` after every render where `value` has changed. The `useEffect` runs *after* render, so `ref.current` will always hold the value from the *previous* render cycle when the component initially renders, allowing for comparisons with the current value.