React.useRef
with initialization callback
import { useLazyRef } from '@vtaits/use-lazy-ref';
const ref = useLazyRef(() => getRefInitialValue());
- No extra boilerplate.
- Inferred type of ref.
- Typescript knows that a value of ref cannot be
undefined
(if it's not a possible result ofgetRefInitialValue
).
import { useRef } from 'react';
const ref = useRef<ValueType>();
if (!ref.current) {
ref.current = getRefInitialValue();
}
- Extra boilerplate.
- Ref type must be set.
- Typescript thinks value of ref can be
undefined
.