DEV Community

xianzhangvs
xianzhangvs

Posted on

Is this a "nested function call" to a hook?

This is the rule of calling hooks:

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns.

For the usage in HOC like below taken from https://github.com/launchdarkly/react-client-sdk/blob/e2f79f1c156e5e82f70cd88fd2bf22dc3be8ecad/src/withLDConsumer.tsx#L43:

function withLDConsumer(options: ConsumerOptions = { clientOnly: false }) {
  return function withLDConsumerHoc<P>(WrappedComponent: React.ComponentType<P & LDProps>) {
    return (props: P) => (
      <Consumer>
        {({ flags, ldClient }: LDContext) => {
          if (options.clientOnly) {
            return <WrappedComponent ldClient={ldClient} {...props} />;
          }

          return <WrappedComponent flags={flags} ldClient={ldClient} {...props} />;
        }}
      </Consumer>
    );
  };
}

Enter fullscreen mode Exit fullscreen mode

Can I use hooks in the returned anonymous function, like below?

function withLDConsumer(options: ConsumerOptions = { clientOnly: false }) {
  return function withLDConsumerHoc<P>(WrappedComponent: React.ComponentType<P & LDProps>) {
    return (props: P) => (
      const [name, setName] = useState('Mary'); 
      <Consumer>
        {({ flags, ldClient }: LDContext) => {
          if (options.clientOnly) {
            return <WrappedComponent ldClient={ldClient} {...props} />;
          }

          return <WrappedComponent flags={flags} ldClient={ldClient} {...props} />;
        }}
      </Consumer>
    );
  };
}
Enter fullscreen mode Exit fullscreen mode

I think it is a "always use Hooks at the top level of your React function", but my friend said it is a "nested function". My understanding to this is that this "nest" should only count from the function component level.

Top comments (1)

Collapse
 
xianzhangvs profile image
xianzhangvs

Additionally saw reduxjs is using a similar pattern:

github.com/reduxjs/react-redux/blo...

so I guess this should be correct. But would like to have more supports.