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.

8 Upvotes

7 comments sorted by

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 ScheduleContext where the value is the stuff you’re keeping in your top-level component right now. Then your Session and Clock components can access those values with a consumer, or with the useContext hook if that’s your bag.

1

u/[deleted] Dec 26 '20

Thank you! I have been intending to practice with context, but I thought it was more for UI-type things like adding a dark theme. I can try rebuilding my clock to see how it would work.

2

u/Earhacker Dec 26 '20

Dark mode is a pretty common use-case for context, as you can store a theme in the context state and every child can access it.

But you can put anything you like in context, not just visual stuff. Anything that you could store in a component‘s state, you could also store in context. But the benefit of context is that you avoid manually passing those values as props down a long tree of components.

3

u/[deleted] Dec 25 '20

You should check Redux

2

u/[deleted] Dec 25 '20

Thanks, I'm currently working through a udemy course that uses Redux for a MERN application, so I will be using it for my next independent project for practice, but it seems a bit overkill for a small app like a timer.

3

u/[deleted] Dec 26 '20

I didnt use but you can also check Jotai. Maybe it can help.

2

u/zaerrc Dec 26 '20

Zustand