Shadcn Hooks

useCreation

A hook to create a value only once

Loading...

Installation

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

Copy and paste the following code into your project.

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
}

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): T

Credits

Last updated on