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.
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 |
clearFnDeps | ReadonlyArray |
Identities that the |
- Ludvig Aldén @ludvigalden