Shadcn Hooks

usePrevious

A hook to get the previous value of a variable

Loading...

Installation

npx shadcn@latest add @hooks/use-previous
pnpm dlx shadcn@latest add @hooks/use-previous
yarn dlx shadcn@latest add @hooks/use-previous
bun x shadcn@latest add @hooks/use-previous

Copy and paste the following code into your project.

use-previous.ts
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 usePrevious

API

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 | undefined

Credits

Last updated on