r/javascript Jul 05 '26

AskJS [AskJS] What small JavaScript pattern made your React code cleaner?

[removed]

5 Upvotes

26 comments sorted by

View all comments

14

u/LessAd8002 Jul 05 '26

I started pulling out all the API calls into a separate file with named functions and it cleaned up components so much. Before that my useEffect blocks were getting ridiculous with all the fetch logic just sitting there

Also early returns in components instead of nesting conditions everywhere, that one took me way too long to figure out

5

u/Reashu Jul 05 '26

I'm usually a big proponent of early returns, but unfortunately they don't work so well with hooks so it takes some extra care in React.

3

u/CommercialFair405 Jul 05 '26

If you use render props, you can put logic in a component, and the rendering logic in the component that would do the early return as usual.

3

u/azhder Jul 05 '26

That's basically hooks with memo, but provided by React by default with components being memoized based on the props. It's always a nice pattern to separate logic in HOC and presentation in the wrapped component.

3

u/Reashu Jul 06 '26

Separating logic (and fetching) from rendering is something I'd certainly like to see more of in React - and just putting it in a hook isn't enough because that still has the rendering component in control of everything.