React introduced hooks earlier this year.

For the most part, I like them. They make code more readable, if sometimes a little cluttered, especially if you useState for single vars.

And they looked like a the perfect solution for a setup I was working on:

  • logic that used state
  • in a containing component (the definition of some accordion panels)
  • and in an additional component (those panels, rendered with a .map())

and I wanted to avoid the confusion and maintenance of making sure everything retrieved and then passed the same redux-derived items as arguments. I also prefer DRY code.

So I wrote up a hook that pulled store.getState() and did some stuff — including running a validator. My innermost components were accurate. GREAT! But my outermost ones didn’t change after their first render.

I read and re-read the Rules of Hooks, and got some pleasant cleanup here and there in my app. But somehow I missed a big point until googling finally got me here:

 

Custom hooks can’t be lifted out of components that are rendered inside of conditions or loops.

when To use React hooks

Ouch. I knew not to call them in the render method. But I was trying to use the hook at a “lifted” level, and it wasn’t working.

The problem wasn’t my hook — it was the lifecycle of that component.

So my options:

  • Park these items in selectors
  • Have the child component set state upstream. (Weird but possible, and not at ALL decoupled)
  • Move the logic result into the redux store
  • (Repetitively) pass the relevant objects as arguments to regular old functions from the multiple connected components.

I’m still thinking on it. Gotta take the dog to the vet.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *