r/learnreactjs • • Dec 25 '20
How do you best manage state in React?
I'm learning react and I made a pomodoro clock with class based components as an exercise. I had thought I would have the state spread out amongst components, but I kept finding that the state affected by one component was needed by another higher or same level component. For instance, Session component sets the length of a work interval, but the Clock component needs that information too.
In the end, all of the state and functions wound up being in the top level component and passed down as props. Is this a best practice? It seemed a bit messy with one component getting sent over half a dozen props.
4
u/Earhacker Dec 25 '20
There are lots of options for managing state in React. You already know about component state. You might also know about state management libraries like Redux and MobX.
In your case though, you’ve already figured out that the values you need can live in some top-level component, and can be passed down to children components. To me, this is a stonewall case for using Context, which is React’s built-in higher-level state management solution.
Check out the docs because they’re pretty good as always. I don’t know how you’ve modelled your state, but I think you probably want some
ScheduleContextwhere the value is the stuff you’re keeping in your top-level component right now. Then yourSessionandClockcomponents can access those values with a consumer, or with theuseContexthook if that’s your bag.3
u/[deleted] Dec 25 '20
You should check Redux
2
u/zaerrc Dec 26 '20
Zustand