Skip to content

Latest commit

 

History

History
45 lines (34 loc) · 2.77 KB

README.md

File metadata and controls

45 lines (34 loc) · 2.77 KB

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.