3
1 Comment

My thought process when creating a useToggle() React hook 🕹

I recently shared this tweet, which generated some interesting discussion.

As Paul mentions, the first method may be totally fine for you and it's really about ref equality, not cost of creating a new function. If you're passing toggle down to child components then you may want ref equality to avoid extra renders.

Whichever way you go though, you'll want to use a function argument for useState to avoid this bug.

And finally, this can also be implemented with useReducer. As always, the best way to learn is to share your solution publicly and wait for people to tell you how it can be done better :)

  1. 2

    Thanks for sharing, my hook knowledge is pretty shallow. I'm gonna have to read this more carefully when my brain is less tired. I recently tried making a custom hook to detect mouse double-clicks... basically I randomly tried different things with useState, useRef and useCallback until I got it to work how I wanted 🙄

Trending on Indie Hackers
Passed $7k 💵 in a month with my boring directory of job boards 35 comments Reaching $100k MRR Organically in 12 months 31 comments 87.7% of entrepreneurs struggle with at least one mental health issue 14 comments How to Secure #1 on Product Hunt: DO’s and DON'Ts / Experience from PitchBob – AI Pitch Deck Generator & Founders Co-Pilot 11 comments Competing with a substitute? 📌 Here are 4 ad examples you can use [from TOP to BOTTOM of funnel] 10 comments Are you wondering how to gain subscribers to a founder's X account from scratch? 9 comments