codedsaif-react-hooks
Version:
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
26 lines (23 loc) • 672 B
JavaScript
import { useRef, useEffect } from "react";
/**
* Custom hook to get the previous value of a prop or state.
* @param {*} value - The current value to track.
* @returns {*} - The previous value before the current render.
* @example
* const [count, setCount] = useState(0);
* const prevCount = usePrevious(count);
* return (
* <>
* <p>Current: {count}, Previous: {prevCount}</p>
* <button onClick={() => setCount(count + 1)}>Increase</button>
* </>
* );
*/
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
export default usePrevious;