DEV Community

Discussion on: Big useEffect mistake

 
aslemammad profile image
Mohammad Bagher Abiyat

Thanks, I appreciate that. The thing that I should say, is that don't worry. when it's too big, split it, or maybe use a good state-management library like jotai and zustand, or server-state-management library like react-query.

Thread Thread
 
nibtime profile image
nibtime

if you are just learning React, I can really recommend zustand as a first state manager, because I feel zustand is what unopinionated useState actually should have been in the first place.

jotai (which is very similar to recoil) is great too. It provides a great solution to the state management problem, just in a different way. If you have an FP background, jotai will feel natural right away, if not going with zustand will be easier I suppose.

when I learned React, I went with plain useState, because Redux was too much for me. But as I progressed I always had the feeling there's something is missing but couldn't really tell what it was.

And it has something to do with deeply nested state: useState doesn't deliver good answers for that, and then something like the JSON.stringify hack pops up. You know you shouldn't do it, but what else should you do?

zustand provides a good solution for that. It allows you to define a possibly very deep object structure and a setter for deep partial updates. You do that outside of React with a create function that will provide you a hook to use the structure and the setter inside React components. This hook gives you the ability to [select slices of that state] as you need them.

When you think about dependencies of useEffect and large, deeply nested object structures, ideally you would like to say "collect n primitive values from somewhere in the structure and return them as an array I can pass to useEffect".

And you exactly say that with the "state array picks" of zustand.

I hope this can help you a little on your React journey.

Thread Thread
 
aslemammad profile image
Mohammad Bagher Abiyat

Great explanation!

Thread Thread
 
benhammondmusic profile image
Ben Hammond

Thanks to you both! I’ll check these out once I move beyond the simple apps I’m playing with now. I heard an interview with the guy behind React Query on Syntax.fm and it sounded like it solved a lot of these problems and more. To the google I go!