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