useLatest
A hook to get the latest value of a variable
useLatest
npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-latest.json"
pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-latest.json"
yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-latest.json"
bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-latest.json"
Copy and paste the following code into your project.
import { useRef } from 'react'
import { useIsomorphicLayoutEffect } from '@/registry/hooks/use-isomorphic-layout-effect'
export function useLatest<T>(value: T) {
const ref = useRef(value)
useIsomorphicLayoutEffect(() => {
ref.current = value
})
return ref
}
credits
Last updated on