Skip to content

Instantly share code, notes, and snippets.

@fmontone
Last active March 16, 2020 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmontone/c473b31f8c9eeb9070eba7f4db802f8a to your computer and use it in GitHub Desktop.
Save fmontone/c473b31f8c9eeb9070eba7f4db802f8a to your computer and use it in GitHub Desktop.
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