Krigga
Krigga

Reputation: 13

Is it fine to use useCallback inside another function?

I have (TypeScript) code like the following:

export const DemoComponent = React.memo((props: DemoComponentProps) => {
    const [state1, setState1] = React.useState<string | undefined>('');
    const [state2, setState2] = React.useState<string | undefined>('');
    const createF = (b: boolean) => React.useCallback(() => {
        /* code that does not depend on b or state2 */

        doSomething({ param: 'param', param2: b ? undefined : state2 });

        if (!b) setState2(/* some other value */);
    }, b ? [state1] : [state1, state2]);
    const f1 = createF(false);
    const f2 = createF(true);

    return (
        /* a few components, some of which use f1, while others use f2 */
    );
});

Will useCallback work as expected here (as if I just wrote it twice for f1 and f2 and rewrote all places that use b) or will it go wrong?

Upvotes: 0

Views: 6851

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

You can't use useCallback like so due to Rules of Hooks.

Don’t call Hooks from regular JavaScript functions.

  • Call Hooks from React function components.
  • Call Hooks from custom Hooks

Hooks must be called on top-level of the function component.

Moreover, you should get eslint warning for it: react-hooks/rules-of-hooks

React Hook "useCallback" is called in function ... which is neither a React function component or a custom React Hook function.

Upvotes: 2

Related Questions