|
| 1 | +# useLazyRef |
| 2 | +Hook that works 'partially' like the _useState_ hook with lazy initialization: ensures that the __initializer__ function is executed only once. |
| 3 | + |
| 4 | +## Usage |
| 5 | + |
| 6 | +```tsx |
| 7 | +const initializer = () => { |
| 8 | + console.log("initializer run...") |
| 9 | + return Array(100).fill(true).reduce((prev, curr, index) => prev + index, 0); |
| 10 | +} |
| 11 | + |
| 12 | +const initializerLazy = () => { |
| 13 | + console.log("initializerLazy run...") |
| 14 | + return Array(100).fill(true).reduce((prev, curr, index) => prev + index, 0); |
| 15 | +} |
| 16 | + |
| 17 | +export const UseLazyRef = () => { |
| 18 | + const rerender = useRerender(); |
| 19 | + const [apply] = useInterval(() => rerender(), 1000); |
| 20 | + const lazyValue = useLazyRef(initializerLazy); |
| 21 | + const value = useRef(initializer()); |
| 22 | + |
| 23 | + apply(); |
| 24 | + |
| 25 | + return ( |
| 26 | + <div> |
| 27 | + <p>Value is: {value.current}</p> |
| 28 | + <p>LazyValue is: {lazyValue.current}</p> |
| 29 | + </div> |
| 30 | + ); |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | +> There are two functions __initializer__ and __initializerLazy__ that log a message when they runs then sum and return number from 0 to 100. |
| 35 | +> |
| 36 | +> The component has: |
| 37 | +> - a __lazyValue__ creates by _useLazyRef_ hook with __initializerLazy__ function as param. |
| 38 | +> - a __value__ creates by _useRef_ hook with __initializer__ function executed as param. |
| 39 | +> - a __rerender__ function created by _useRerender_ hook to force a rerender. |
| 40 | +> - a __apply__ function created by _useInterval_ hook to execute __rerender__ function every second. |
| 41 | +> - render a div with __lazyValue__ and __value__ values. |
| 42 | +> |
| 43 | +> If you open devtools will see that __initializerLazy__ message is logged once while __initializer__ message every rerender. |
| 44 | +
|
| 45 | + |
| 46 | +## API |
| 47 | + |
| 48 | +```tsx |
| 49 | +useLazyRef <T>(initializer: () => T): React.MutableRefObject<T> |
| 50 | +``` |
| 51 | + |
| 52 | +> ### Params |
| 53 | +> |
| 54 | +> - __initializer__: _()=>T_ |
| 55 | +> |
| 56 | +
|
| 57 | +> ### Returns |
| 58 | +> |
| 59 | +> |
| 60 | +> - _React.MutableRefObject<T>_ |
| 61 | +> |
0 commit comments