Skip to content

Instantly share code, notes, and snippets.



Last active Mar 16, 2020
What would you like to do?
Custom React Hook to save previous state (or undefined as default)
import { useRef, useEffect } from 'react';
* Custom React Hook usePrevious
* @returns ref.current {current: "ANY"}
* @default undefined
* @description It store the previous state when state changes.
* @example const previousState = usePrevios(state)
export function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment