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
How I grew a side project to 100k Unique Visitors in 7 days with 0 audience 49 comments Competing with Product Hunt: a month later 33 comments Why do you hate marketing? 29 comments My Top 20 Free Tools That I Use Everyday as an Indie Hacker 18 comments $15k revenues in <4 months as a solopreneur 14 comments Use Your Product 13 comments