Managing States With Redux Toolkit
Ever felt that configuring a Redux store is too complicated, or that you have to add a lot of packages to get Redux to do anything useful, or that redux requires too much boilerplate code. If yes here is the perfect way to reduce these common redux concerns and that is Redux Toolkit. The Redux Toolkit package is intended to be the standard way to write Redux logic.
In this article you will understand how to use Redux Toolkit using a React application that shows a list of random users.
Setting Up Redux Toolkit
# If you use npm:
npm install @reduxjs/toolkit
npm install react-redux
# Or if you use Yarn:
yarn add react-redux
yarn add @reduxjs/toolkit
Creating The Store For Redux
To create the Redux store, create a file named src/store/index.js
. Then import the configureStore
API from Redux Toolkit. We'll start by creating an empty Redux store, and exporting it:
Providing The Redux Store To React
Once our store is created, we can make it available to our React components by putting a React-Redux <Provider>
around our application in src/index.js
. Import the Redux store we just created, put a <Provider>
around your <App>
, and pass the store as a prop:
Create a Redux State Slice
Now we create a new file named src/store/user/userSlice.js
. In that file, import the createSlice
API from Redux Toolkit.
To create a slice we need a string name to identify the slice, an initial state value, and one or more reducer functions to describe how the state can be modified. Once a slice is initialized, we can export the generated Redux action creators and the reducer function for the whole slice.
Add The Created Slice Reducers to the Store
We then need to import the reducer function from the user slice and add it to our store. By defining a field inside the reducer
parameter, we tell the store to use this slice reducer function to handle all updates to that state.
Use Redux State and Actions in React Components
Now we can use the React-Redux hooks to let React components interact with the Redux store. We can read data from the store with useSelector
, and dispatch actions using useDispatch
.
I hope you enjoyed and found this Redux Toolkit tutorial informative. The full code repository presented in this article can be found on Github