Skip to content

Instantly share code, notes, and snippets.

@natterstefan
Created August 30, 2022 11:07
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 natterstefan/c049c34cba32e5378429ecbd4dcec65a to your computer and use it in GitHub Desktop.
Save natterstefan/c049c34cba32e5378429ecbd4dcec65a to your computer and use it in GitHub Desktop.
React | usePrevious hook
/**
* 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