JAVASCRIPT
Storing Previous State or Prop Value with React's usePrevious Hook
Learn to create a custom React hook, usePrevious, to efficiently store and access the previous value of any state or prop, enhancing component 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>
// <h1>Current: {count}, Previous: {prevCount}</h1>
// <button onClick={() => setCount(count + 1)}>Increment</button>
// </div>
// );
// }
How it works: This `usePrevious` hook leverages `useRef` to store a mutable value that persists across renders without causing re-renders itself. The `useEffect` hook updates the `ref.current` to the latest `value` *after* the render, ensuring that on the *next* render, `ref.current` holds the value from the *previous* render. This is useful for comparing current and past states or props.