UNPKG

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