use-creation

PreviousNext

A hook to create a value only once

Docs
hookshook

Preview

Loading preview…
registry/hooks/use-creation.ts
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
}

Installation

npx shadcn@latest add @hooks/use-creation

Usage

import { UseCreation } from "@/hooks/use-creation"
const value = UseCreation()