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
After 10M+ Views, 13k+ Upvotes: The Reddit Strategy That Worked for Me! 42 comments Getting first 908 Paid Signups by Spending $353 ONLY. 23 comments 🔥Roast my one-man design agency website 21 comments What are your cold outreach conversion rates? Top 3 Metrics And Benchmarks To Track 19 comments I talked to 8 SaaS founders, these are the most common SaaS tools they use 18 comments Hero Section Copywriting Framework that Converts 3x 12 comments