DEV Community

Cover image for Redux Toolkit, managing states in React
Luis "shadowtampa" Gomes
Luis "shadowtampa" Gomes

Posted on

Redux Toolkit, managing states in React

React States. How do you manage them? When your application is quite small, it is okay (but not recomendable) to prop drill states. But when you have at least 5 different components or "grandson - grandfather" relationships, you need to have a solid management or your system will succumb.

What are my options?

If you are dealing with small aplications, there is no shame on utilizing useContext. It is actually quite interesting the fact that you can write your own hooks. The greatest thing about useContext is it simplicity. Write down a provider, a consumer and your hook, and you are all set. The only reason that I quit utilizing useContext was the Provider declaration. You need to wrap your main div with a provider component and that really sucks when you have 4 or more hook necessities. What leads to our next option:

Redux Toolkit
Redux flow
Firt things first, dont be scaried. Altought redux is a frightening word, it use is fairly simple. You need only:

  • A store component
  • A provider
  • A slice
  • A selector and a dispatcher

Store Component

The Redux store is the main component that makes all your slices available for other components. Unlike useContext, you just need to wrap your main component with a single Provider. Think as a "switch".

Provider

It is a component that you will wrap the main component or your application. It is only required once. That is the way that you are going to utilize the Store Component

Slice

Probaly you are wondering "what the heck is a slice?". A slice is your command center for managing a state. In simple backends you have a controller. A slice is nothing more than a Slice. In this component you are able to receive requests, alter states, fetch results from state and mutate then, both sync and async. For that, you'll need reducers, that are analogue to Controller methods. Sou you can have a "create reducer", a "update", and so, untill you have a CRUD.

selector and a dispatcher

Okay, you did set up your application, but how you fetch and mutate data in your components? Trough selectors and dispatchers. Selector is the way you are going to fetch data (both the whole state or destructure some props) and Dispatcher is the mutators of the data, the way you are going to utilize the CRUD reducers, for instance.

Conclusion

Redux Toolkit is the way to go for your applications, since you dont want to be stuck with multi-providing or prop drilling issues. So, dont be afraid, take a read on https://redux-toolkit.js.org/introduction/getting-started and fire on this trouble!

Top comments (0)