UNPKG

653 BJavaScriptView Raw
1import { useRef } from 'react';
2var dft = Symbol('default value sigil');
3/**
4 * Exactly the same as `useRef` except that the initial value is set via a
5 * factroy function. Useful when the default is relatively costly to construct.
6 *
7 * ```ts
8 * const ref = useRefWithInitialValueFactory<ExpensiveValue>(() => constructExpensiveValue())
9 *
10 * ```
11 *
12 * @param initialValueFactory A factory function returning the ref's default value
13 * @category refs
14 */
15
16export default function useRefWithInitialValueFactory(initialValueFactory) {
17 var ref = useRef(dft);
18
19 if (ref.current === dft) {
20 ref.current = initialValueFactory();
21 }
22
23 return ref;
24}
\No newline at end of file