top | item 44722491

(no title)

codemonkey-zeta | 7 months ago

I agree that this is the approach that keeps react apps simple. The biggest problems I see in react code are giant components that read like this:

useState

useState

useState

... // 20 more

useEffect

useEffect

useEffect

... // 20 more

I think a lot of front-end devs don't realize the necessity of custom hooks for composition and modularization. My personal rule is "Never use react hooks (useState, useEffect, etc.) in component code. All react hooks MUST be wrapped by custom hooks." and it makes for MUCH better code:

useSomeData

useOtherData

useMobileView

useScrollToTop

useInteractionLogging

... // 10 more hooks

This is also what makes TanStack so good and popular. It's all just behavior wrapped in hooks.

discuss

order

matsemann|7 months ago

This I disagree on. Unless the hook is to be reused, just chuck it in your component where it's actually used. Yeah, it's pretty if you can decompose it cleanly. But if you end up with calling useX, and passing a statement function from that to useY etc, it's just a mess figuring out what's going on. Just chuck it all in the component and skip the abstractions.

skydhash|7 months ago

For very small local state, I can agree. But if you three or more standard hooks that interact together, it’s worth it to wrap it in a custom hook even if it’s going to be in the same file. The semantics will be clearer and working with the code easier. I much prefer to see useFlashyAnimation than its code in the component.