The only React hook you will need for boolean states

Fernando Abolafio
The Startup
Published in
2 min readOct 25, 2020

--

Toggling Modal visibility; hiding, and showing messages, there are many scenarios where you’ll find yourself writing the same code. But there's a solution: useBooleanState

The useBooleanState hook

Going straight to the code, this is how it looks:

How to use it?

I give you an example. Let’s say you want to toggle a Modal visibility. One option would be something like this:

That’s basically the same code structure you would use every time you want to toggle something. Visibility, states (enabled, disabled, etc), the list keeps going.

Let’s see how it looks when we use the useBooleanState hook:

Same code, way less lines and verbosity. The semantic and the functionality is kept. That’s it.

Conclusion

I saw similar hooks out there where a different naming is used like ‘useToggle’ or…

--

--

Fernando Abolafio
The Startup

Programmer — Modeling Revenue in code @GrowblocksHQ — Writing about Web Dev/React/Remix/NextJs — Software Architecture