DEV Community

Cover image for Redux Slice ๐Ÿ•
marinashafiq
marinashafiq

Posted on

Redux Slice ๐Ÿ•

If youโ€™re familiar with redux then you can get the most of this article.
In this article we will not cover the Redux concept itself we will take a slice ๐Ÿ•

The Traditional Way
Each time you want to work with Redux, you need to create Types, Actions, and Reducer to be able to set create redux cycle but with the Redux toolkit, itโ€™s much simpler.

Redux Toolkit Way
It was created to help address some of the redux concerns like โ€œRedux requires too much boilerplate codeโ€, It has functions that build according to redux best practices It includes several utility functions that simplify the most common Redux use cases.
So it provides functions such as createSlice that we will be talking about in this article.

Installation :
npm install @reduxjs/toolkit

You can check more about the Redux toolkit from this link:
https://redux.js.org/redux-toolkit/overview

Now itโ€™s time to CreateSlice()๐Ÿ•

1- How to Create it!

Itโ€™s a function that accepts an object of :

  • Slice name
  • Initial state value
  • Reducers object that contains Reducer functions and its key names will be used to generate actions โ€” these functions intended to handle a specific action type, equivalent to a single case statement in a switch โ€” and each function has a state as the current value in the store and action that will carry the payload for the updated value.

It will automatically generate a slice reducer with corresponding action creators and action types in the background.

Hereโ€™s an example for the Slice file:

2- Add it to reducers

In combine reducers add the slice name as a key :

or you can follow the other way using redux toolkit way but using configureStore() function that takes reducers as one of its parameters.

You can check more about configureStore() from the following link :
https://redux-toolkit.js.org/api/configureStore

3- Dispatch the Action

You can now dispatch the action in your component with exported names that you have added at the end of the slice file such as increment or decrement in our example above.


Summary

You can keep using the traditional way of using the Redux cycle without the need for the redux toolkit, but if you decided to use the redux toolkit it will save you from the repeated redux configuration.

And also you will find this recommendation in the Redux docs :
However, we strongly recommend using Redux Toolkit for all Redux apps.

If youโ€™re already using redux, all you need to do is installing the redux toolkit and create a slice with a name, initial state, and reducer object with functions that will be dispatched as actions later.

Thanks a lot for your time to read this article.
Happy learning!

Top comments (0)