Home:ALL Converter>How to avoiding repeating work (or to keep common/shared state) in nested hooks?

How to avoiding repeating work (or to keep common/shared state) in nested hooks?

Ask Time:2022-04-07T17:12:23         Author:Qtax

Json Formatter

In a nested hook: how could one know if it already was invoked in the current component (instance) and access any previously computed/saved values?

Preferably without the Component author/the hook user having to know about this and not having to do anything special for it to work.

Example

An example to illustrate the problem:

const useNestedHook = () => {
    // Some heavy work with the same result for each component instance.
    // Is it possible to remember the result of this work when
    // this hook is used again in the same component instance?

    // So I would like to save a state which all uses of useNestedHook
    // could access as long as they are in the same component instance.
}

const useHookA = () => {
    useNestedHook();
};

const useHookB = () => {
    useNestedHook();
};

const Component = () => {
    useHookA();

    // Would like to avoid useNestedHook repeating its work since it's
    // used in the same component and would have this same result (per definition)
    // Preferably without the Component author having to know anything about this.
    useHookB();
};

Imagined solution

Something like a "named" shared state, which would give access to the same shared state (in the same component instance) no matter which hook it's used in. With each component instance having its own separate state as usual. Maybe something like:

const [state, setState] = useSharedState("stateId", initialValue);

Author:Qtax,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71779373/how-to-avoiding-repeating-work-or-to-keep-common-shared-state-in-nested-hooks
yy