use-cleared-memo
TypeScript icon, indicating that this package has built-in type declarations

1.4.3 • Public • Published

Stable Release Types Included GZip Size Treeshaking Blazing Fast license


Are you building a hook or functional React component that needs to predictably clear and/or hydrate memoized values in an easy-to-use way? Opportunities are almost endless; no matter if you're subscribing to external state, initializing timers or intervals, or creating a new instance of some object every time deps change that eventually needs to be deconstructed, useClearedMemo will be there for you to do the job.

useClearedMemo(getFn, clearFn, deps, clearFnDeps) ⇒ T

Allows for clearing a memoized value when dependencies change as well as on unmount. The code below is a simplified version of the functionality, which omits the critical fact that the every value that has been retrieved will be cleared before the next one is retrieved or when the component unmounts*. That means every retrieved value will be cleared, and only once. The most obvious use-case for this is creating subscriptions, which either just needs to get unsubscribed on unmount or hydrated when a new subscription should be created (based on the deps).

 React.useMemo(() => {
   clearFn(value);
   return getFn();
 }, deps);
+ React.useEffect(() => clearFn, deps);
≈ useClearedMemo(getFn, clearFn, deps);

Kind: global function
Returns: T -

The value to be memoized and cleared appropriately.

Param Type Description
getFn function

Returns the memoized value that is to be cleared.

clearFn function

Clears the previously memoized value when the component unmounts or the deps change.

deps ReadonlyArray

Identities that the getFn depends on. When changed, the previously memoized value will be cleared and the getFn will be called to retrieve the new value.

clearFnDeps ReadonlyArray

Identities that the clearFn depends on.

Authors


MIT License.

Package Sidebar

Install

npm i use-cleared-memo

Weekly Downloads

13

Version

1.4.3

License

MIT

Unpacked Size

25 kB

Total Files

13

Last publish

Collaborators

  • ludvigalden