useConstant.ts 365 B

12345678910111213141516171819
  1. 'use client'
  2. // based on https://github.com/Andarist/use-constant
  3. import { useRef } from 'react'
  4. type ResultBox<T> = { v: T }
  5. /**
  6. * React hook for creating a value exactly once
  7. */
  8. export function useConstant<T>(fn: () => T): T {
  9. const ref = useRef<ResultBox<T> | null>(null)
  10. if (!ref.current) {
  11. ref.current = { v: fn() }
  12. }
  13. return ref.current.v
  14. }