DEV Community

Discussion on: Conditional hooks?

Collapse
 
alexgulmi profile image
Alexander Gundermann • Edited
  1. I think that's the best approach. Your example could be improved though, because if you now try to use a hook inside the shouldBeUsed you will run into the same problem. You would have to make sure not to attach any listeners, call setState etc, which depends a lot on what the hook actually does.

  2. Interesting approach, but I think there are a few problems with this the way you wrote it:

  • you create a different HookComponent on every render, thus causing everything to re-mount. Could be mitigated by putting the component and the latest props into a ref, or by making it a stand-alone component that takes the ref, hook props, and hook function via props
  • toggling condition will change the react render tree structure and thus cause all children to re-mount
  • the hook only runs after the main component MyFC is rendered, since it'll be deeper in the react tree, so output should be one render cycle behind. I guess that's okay if the hook doesn't return anything. In other cases, I think you'd have to re-structure it so that the hook component is a parent of MyFC

Maybe you could mitigate most of these issues with a render structure like this:

<HookWrapper>
  <HookComponent /> // conditionally rendered
  <MyFC />
</HookWrapper>
Enter fullscreen mode Exit fullscreen mode

There's also a third option of ignoring the lint rule if you're sure that the condition never changes.

Collapse
 
lexlohr profile image
Alex Lohr

Thanks for your comment. Yes, an issue with 1. caused me to consider 2. - in any case, I found a work around for 1., but didn't want the thought go to waste.

Also thanks for the hint, I changed the code to now memoize the component.

I did not yet publish a package, but wanted to publish this a POC. I'll have a look into the wrapper structure some time later.