1.0.0 • Published 2 years ago

@utilityjs/use-lazy-initialized-value v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

A React hook that holds a lazy-initialized value for a component's lifecycle.

license npm latest package npm downloads types

npm i @utilityjs/use-lazy-initialized-value | yarn add @utilityjs/use-lazy-initialized-value

This hook calls the provided initFactory on mount and returns the factory value for the duration of the component's lifecycle. See React docs on creating expensive objects lazily.

Comparison to useMemo

You may rely on useMemo only as a performance optimization, not as a semantic guarantee. React may throw away the cached value and recall your factory even if deps did not change.

Comparison to useState

You can get the same result using useState(factory)[0], but it's a little more expensive supporting unused update functionality.

The right way is to implement it using useRef as described in React doc's how to create expensive objects lazily. However, useLazyInitializedValue is likely more convenient and hides the ref.current implementation detail.

Usage

const Component = () => {
  // Creating expensive object lazily
  // Can guarantee that `obj` is always same instance
  const obj = useLazyInitializedValue(() => {
    return createExpensiveObject();
  });

  // ...
}

API

useLazyInitializedValue(initFactory)

declare const useLazyInitializedValue: <T>(initFactory: () => T) => T;