The only React hook you will need for boolean states

Fernando Abolafio
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 ‘useModal’. I rather keep it as generic as possible so other developers are not afraid of employing it whenever they need.

The hook useBooleanState is one of those things a good developer would like to keep in his tool box. I hope you find useful for your future projects. Happy coding.

👉 Follow me on my Medium to support me and get the newest articles straight out of the oven: @fernandoabolafio 🛎

👉 Follow me on Twitter @oxfernando and let’s chat. I post about React, NextJs, Remix.run, and other cool WebDev technologies. 🐤

--

--

Fernando Abolafio

Fullstack Engineer — Modeling Revenue in code @GrowblocksHQ — Tweeting about Web Dev/React/Remix/NextJs — Software Architecture — Blockchain Tech/DAO/Decred