useCreation
A hook to create a value only once
Loading...
Installation
npx shadcn@latest add @hooks/use-creationpnpm dlx shadcn@latest add @hooks/use-creationyarn dlx shadcn@latest add @hooks/use-creationbun x shadcn@latest add @hooks/use-creationCopy and paste the following code into your project.
import { isEqual } from 'es-toolkit/predicate'
import { useRef } from 'react'
import type { DependencyList } from 'react'
export function useCreation<T>(factory: () => T, deps: DependencyList) {
const { current } = useRef({
deps,
obj: undefined as T,
initialized: false,
})
if (current.initialized === false || !isEqual(current.deps, deps)) {
current.deps = deps
current.obj = factory()
current.initialized = true
}
return current.obj
}API
/**
* A hook to create a value only once
* @param factory - The factory function to create the value
* @param deps - The dependencies to create the value
* @returns The created value
*/
export function useCreation<T>(factory: () => T, deps: DependencyList): TCredits
Last updated on