Created
August 30, 2022 11:07
-
-
Save natterstefan/c049c34cba32e5378429ecbd4dcec65a to your computer and use it in GitHub Desktop.
React | usePrevious hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* inspired by | |
* @see https://codesandbox.io/s/use-previous-hook-persistent-with-matcher-hujqez?file=/src/hooks.tsx:0-1069 | |
* @see https://www.developerway.com/posts/implementing-advanced-use-previous-hook | |
* @see https://usehooks.com/usePrevious/ | |
*/ | |
import { useRef, useEffect } from 'react' | |
export const usePrevious = <TValue>(value: TValue) => { | |
const ref = useRef<TValue>() | |
useEffect(() => { | |
ref.current = value | |
}, [value]) | |
// Return previous value (happens before update in useEffect above) | |
return ref.current | |
} | |
export const usePreviousPersistent = <TValue>(value: TValue) => { | |
const ref = useRef<{ value: TValue; prev: TValue | null }>({ | |
value, | |
prev: null, | |
}) | |
const current = ref.current.value | |
if (value !== current) { | |
ref.current = { | |
value, | |
prev: current, | |
} | |
} | |
return ref.current.prev | |
} | |
export const usePreviousPersistentWithMatcher = <TValue>( | |
value: TValue, | |
isEqualFunc: (prev: TValue, next: TValue) => boolean, | |
) => { | |
const ref = useRef<{ value: TValue; prev: TValue | null }>({ | |
value, | |
prev: null, | |
}) | |
const current = ref.current.value | |
if (isEqualFunc ? !isEqualFunc(current, value) : value !== current) { | |
ref.current = { | |
value, | |
prev: current, | |
} | |
} | |
return ref.current.prev | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment