useLatest
A hook to get the latest value of a variable
Installation
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 { useEffect, useLayoutEffect } from 'react'
import { isBrowser } from '@/registry/lib/is-browser'
/**
* Custom hook that uses either `useLayoutEffect` or `useEffect` based on the environment (client-side or server-side).
* @param {Function} effect - The effect function to be executed.
* @param {Array<any>} [dependencies] - An array of dependencies for the effect (optional).
* @public
* @see [Documentation](https://usehooks-ts.com/react-hook/use-isomorphic-layout-effect)
* @example
* ```tsx
* useIsomorphicLayoutEffect(() => {
* // Code to be executed during the layout phase on the client side
* }, [dependency1, dependency2]);
* ```
*/
export const useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffectimport { 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
}API
/**
* A hook to get the latest value of a variable
* @param value - The value to get the latest value of
* @returns The latest value of the variable
*/
export function useLatest<T>(value: T): RefObject<T>Credits
Last updated on