usePrevious
A hook to get the previous value of a variable
Loading...
Installation
npx shadcn@latest add @hooks/use-previouspnpm dlx shadcn@latest add @hooks/use-previousyarn dlx shadcn@latest add @hooks/use-previousbun x shadcn@latest add @hooks/use-previousCopy and paste the following code into your project.
import { useRef } from 'react'
export type ShouldUpdateFunc<T> = (prev?: T, next?: T) => boolean
const defaultShouldUpdate = <T>(a?: T, b?: T) => !Object.is(a, b)
function usePrevious<T>(
state: T,
shouldUpdate: ShouldUpdateFunc<T> = defaultShouldUpdate,
): T | undefined {
const prevRef = useRef<T>(undefined)
const curRef = useRef<T>(undefined)
if (shouldUpdate(curRef.current, state)) {
prevRef.current = curRef.current
curRef.current = state
}
return prevRef.current
}
export default usePreviousAPI
export type ShouldUpdateFunc<T> = (prev?: T, next?: T) => boolean
const defaultShouldUpdate = <T>(a?: T, b?: T) => !Object.is(a, b)
/**
* A hook to get the previous value of a state
* @param state - The state to get the previous value of
* @param shouldUpdate - The function to determine if the state should be updated
* @returns The previous value of the state
*/
export function usePrevious<T>(
state: T,
shouldUpdate?: ShouldUpdateFunc<T>,
): T | undefinedCredits
Last updated on