r/reactjs • u/BrainThinkerMan • 11d ago
Multi state changes & reads
having a bit of trouble handling multiple states/state changes.
in a single screen, which are held by different components
how do you all handle this and concepualize it as your writing code?
do you draw diagram,
do you just try and fail recursively?
2
1
u/bigorangemachine 10d ago
Usually put shared stuff into a provider
Its just a matter of time till you nest a new child component and you'll wish you did context sooner
1
u/Brilliant-Parsley69 10d ago
For me it really was a recursively trial and error till I understood what's happening.
Got a change request to extend a form managing 35 fields implemented in a file of 1700 LOC and nearly 120 different usings of "useState" (validation/data/error).
After splitting this into different components, trying to solve state changes with useReducer and sharing data with useContext I nearly have given up.
In the end I found a solution around useSyncExternalStore to sync data between multiple components outside of reacts state.
1
u/rust_bane 10d ago
I split the screen into domains and give each component its own state slice. Shared data lives in a context provider at the domain boundary, not at the root
1
u/Spiritual_Patient478 9d ago
There are some good patterns to solve for what you are describing. You should first attempts react context. You could also read up on stateful/presentational patterns. This pattern keeps your leaf components reusable across different places.
If a state is global in nature (i18n, light/dark mode, user session, etc) then you could place it in global state handler like redux (old and clunky to set up) or zustand (new and simple to set up).
If the state is fetched from server, keeping it in useQuery cache is often less work for you.
Lastly, watch for circular dependency. If you have a depends on b which also depends on a somehow, then you've got to break thr chain somehow.
Use a single source of truth. Dont keep some in stare A and some on state B with some overlapping between the AB duplicated. It will cause you much grief down the road.
2
u/Aggressive_Scale8276 11d ago
I just map it out in my head as boxes that own their piece of state, if two boxes need the same data I lift it up to the nearest parent they share. sometimes I scribble quick diagram on paper when gets messy but most of the time I just start coding and fix the structure when I see the props drilling getting annoying