JAVASCRIPT
React usePrevious Hook to Track Previous State
Discover how to implement a usePrevious hook in React to easily access the prior value of a prop or state, essential for comparisons within useEffect or other logic.
import { useRef, useEffect } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
How it works: The `usePrevious` hook allows you to get the value that a prop or state had on the previous render. It stores the current value in a `useRef` on each render and returns its value from the *previous* render. This is particularly useful for comparing current and past values within a `useEffect` hook to trigger specific side effects.