Type something to search...
React With Redux Toolkit

React With Redux Toolkit

Prerequisites

This post assumes that you have a basic understanding of React and Redux. and it will be better if you have some experience with React Hooks like useReducer.

Introduction

Nowadays, we have a lot of state management libraries for React, such as Redux, MobX, and Recoil. In this post, we will learn how to use Redux Toolkit to manage the state of our React application.

What is Redux?

Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.

What is Redux Toolkit?

Redux Toolkit is the official, opinionated, batteries-included toolset for efficient Redux development. It is intended to be the standard way to write Redux logic.

It was originally created to help address three common concerns about Redux:

  • Configuring a Redux store is too complicated.
  • I have to add a lot of packages to get Redux to do anything useful.
  • Redux requires too much boilerplate code.

Why Redux Toolkit?

Redux Toolkit is a package that contains a set of tools to help you write Redux logic more easily. It is not a Redux replacement, but it is an alternative to writing Redux logic by hand.

Installation

Step 1: Initialize a React project using vite

First, we need to initialize a React project using vite.

Terminal window
# using npm
npm init vite react-with-redux-toolkit
# using yarn
yarn create vite react-with-redux-toolkit
# using pnpm
pnpm create vite react-with-redux-toolkit
# using npx
npx create-vite react-with-redux-toolkit
Terminal window
# select the react
? Select a framework: react
Terminal window
# select the javascript
? Select a variant: javascript

Note: You can use npm, yarn, pnpm, or npx to initialize a React project using vite.

Note: You can use typescript instead of javascript to initialize a React project using vite.

Step 2: Go to the project directory

Terminal window
cd react-with-redux-toolkit

Step 3: Install Basic Dependencies

Terminal window
# using npm
npm install
# using yarn
yarn install
# using pnpm
pnpm install

Step 4: Install Redux Toolkit

Terminal window
# using npm
npm install @reduxjs/toolkit react-redux
# using yarn
yarn add @reduxjs/toolkit react-redux
# using pnpm
pnpm add @reduxjs/toolkit react-redux

Usage

Step 1: Remove the unnecessary files

We will remove the unnecessary files, or we can say that we will clean up src directory.

Terminal window
rm -rf src/*

Explanation:

  • rm - remove files or directories
  • -rf - remove directories and their contents recursively

Step 2: Create the Basic Structure

Step 2.1: Create the Folders and Files

We will create the basic structure of our project.

Terminal window
# create the components directory
mkdir src/components
# create the store directory
mkdir src/app
# create the App.jsx file
touch src/App.jsx
# create the main.jsx file
touch src/main.jsx

Step 2.2: Create the App.jsx file

We will create the App.jsx file.

src/App.jsx
1
const App = () => {
2
return (
3
<div>
4
<p>React With Redux Toolkit - Part 1</p>
5
</div>
6
);
7
};
8
9
export default App;

Step 2.3: Create the main.jsx file

We will create the main.jsx file.

src/main.jsx
1
import React, {StrictMode} from 'react';
2
import ReactDOM from 'react-dom/client';
3
import App from './App';
4
5
ReactDOM.createRoot(document.getElementById('root')).render(
6
<StrictMode>
7
<App />
8
</StrictMode>,
9
);

Step 3: Create the Store

Step 3.1: Create the store.js file

We will create the store.js file.

src/app/store.js
1
import {configureStore} from '@reduxjs/toolkit';
2
3
const store = configureStore({
4
reducer: {},
5
});
6
7
export default store;

As you can see, we have imported the configureStore function from @reduxjs/toolkit and we have created the store using the configureStore function.

Explanation:

  • import { configureStore } from '@reduxjs/toolkit' - import the configureStore function
  • const store = configureStore({ reducer: {} }) - create the store using the configureStore function
  • export default store - export the store

Note: We will add the reducer later.

After that we will do some changes to the main.jsx file.

src/main.jsx
1
import React, {StrictMode} from 'react';
2
import ReactDOM from 'react-dom/client';
3
import {Provider} from 'react-redux';
4
import App from './App';
5
import store from './app/store';
6
7
ReactDOM.createRoot(document.getElementById('root')).render(
8
<StrictMode>
9
<Provider store={store}>
10
<App />
11
</Provider>
12
</StrictMode>,
13
);

You’ll notice that we have wrapped the App component with the Provider component after importing it from the react-redux library. Additionally, the store from ./app/store was imported. To the Provider component, we have passed the store.

Explanation:

  • import { Provider } from 'react-redux' - import the Provider component
  • import store from './app/store' - import the store
  • <Provider store={store}> - pass the store to the Provider component

Step 4: Create the counterSlice.js file

We will create the counterSlice.js file.

src/components/Counter/counterSlice.js
1
import {createSlice} from '@reduxjs/toolkit';
2
3
const initialState = {
4
count: 0,
5
};
6
7
const counterSlice = createSlice({
8
name: 'counter',
9
initialState,
10
reducers: {
11
increment: (state) => {
12
state.count += 1;
13
},
14
decrement: (state) => {
15
state.count -= 1;
16
},
17
reset: (state) => {
18
state.count = 0;
19
},
20
incrementByAmount: (state, action) => {
21
state.count += action.payload;
22
},
23
},
24
});
25
26
export const {increment, decrement, reset, incrementByAmount} =
27
counterSlice.actions;
28
29
export default counterSlice.reducer;

The createSlice function is used to create a slice of the store. We have passed the name of the slice as counter. We have passed the initial state of the slice as initialState. We have passed the reducers as an object. We have passed the increment, decrement, reset, and incrementByAmount reducers. We have exported the increment, decrement, and incrementByAmount actions. We have exported the reducer.

Explanation:

  • import { createSlice } from '@reduxjs/toolkit' - import the createSlice function
  • const initialState = { count: 0 } - define the initial state of the slice
  • const counterSlice = createSlice({ name: 'counter', initialState, reducers: { increment: (state) => { state.count += 1 }, decrement: (state) => { state.count -= 1 }, reset: (state) => { state.count = 0 }, incrementByAmount: (state, action) => { state.count += action.payload }, } }) - create the slice of the store
  • export const { increment, decrement, reset, incrementByAmount } = counterSlice.actions - export the actions
  • export default counterSlice.reducer - export the reducer

Step 5: Add the counterSlice reducer to the store

We will add the counterSlice reducer to the store.

src/app/store.js
1
import {configureStore} from '@reduxjs/toolkit';
2
import counterReducer from '../components/Counter/counterSlice';
3
4
const store = configureStore({
5
reducer: {
6
counter: counterReducer,
7
},
8
});
9
10
export default store;

Now after adding the counterSlice reducer to the store, it will be available in the entire application.

Explanation:

  • import counterReducer from '../components/Counter/counterSlice' - import the counterSlice reducer
  • reducer: { counter: counterReducer } - add the counterSlice reducer to the store

Step 6: Add the Counter Component to the App Component

We will add the Counter Component to the App Component.

src/components/Counter/Counter.jsx
1
import React from 'react';
2
import {useSelector, useDispatch} from 'react-redux';
3
import {increment, decrement, reset, incrementByAmount} from './counterSlice';
4
5
const Counter = () => {
6
const count = useSelector((state) => state.counter.count);
7
const dispatch = useDispatch();
8
9
return (
10
<div>
11
<p>Count: {count}</p>
12
<button onClick={() => dispatch(increment())}>Increment</button>
13
<button onClick={() => dispatch(decrement())}>Decrement</button>
14
<button onClick={() => dispatch(reset())}>Reset</button>
15
<button onClick={() => dispatch(incrementByAmount(5))}>
16
Increment By 5
17
</button>
18
</div>
19
);
20
};
21
22
export default Counter;

As you can see, we have imported the useSelector hook from react-redux. We have imported the useDispatch hook from react-redux. We have imported the increment, decrement, reset, and incrementByAmount actions from ./counterSlice. We have used the useSelector hook to get the count from the store. We have used the useDispatch hook to dispatch the actions. We have used the increment, decrement, reset, and incrementByAmount actions to dispatch the actions.

Explanation:

  • import { useSelector, useDispatch } from 'react-redux' - import the useSelector hook and the useDispatch hook
  • import { increment, decrement, incrementByAmount } from './counterSlice' - import the actions
  • const count = useSelector((state) => state.counter.count) - get the count from the store
  • const dispatch = useDispatch() - get the dispatch function
  • onClick={() => dispatch(increment())} - dispatch the increment action
  • onClick={() => dispatch(decrement())} - dispatch the decrement action
  • onClick={() => dispatch(reset())} - dispatch the reset action
  • onClick={() => dispatch(incrementByAmount(5))} - dispatch the incrementByAmount action

Step 7: Add the Counter Component to the App Component

We will add the Counter Component to the App Component.

src/App.jsx
1
import React from 'react';
2
import Counter from './components/Counter/Counter';
3
4
const App = () => (
5
<div>
6
<Counter />
7
</div>
8
);
9
10
export default App;

As you can see, we have imported the Counter Component. We have added the Counter Component to the App Component.

Explanation:

  • import Counter from './components/Counter/Counter' - import the Counter Component
  • <Counter /> - add the Counter Component to the App Component

Step 8: Run the application

We will run the application.

Terminal window
yarn dev

Redux Toolkit Counter

As you can see, we have a counter. We can increment the counter. We can decrement the counter. We can increment the counter by 5.

Step 9: Access count value in other components

We will access the count value in other components, for example, in the Header component.

src/components/Header/Header.jsx
1
import React from 'react';
2
import {useSelector} from 'react-redux';
3
4
const Header = () => {
5
const count = useSelector((state) => state.counter.count);
6
7
return (
8
<header>
9
<h1>Redux Toolkit Counter</h1>
10
<p>Count: {count}</p>
11
</header>
12
);
13
};
14
15
export default Header;

As you can see, we have imported the useSelector hook from react-redux. We have used the useSelector hook to get the count value from the store. We have added the count value to the Header component.

Explanation:

  • import { useSelector } from 'react-redux' - import the useSelector hook
  • const count = useSelector((state) => state.counter.count) - get the count from the store
  • <p>Count: {count}</p> - add the count to the Header component

Step 10: Add the Header Component to the App Component

We will add the Header Component to the App Component.

src/App.jsx
1
import React from 'react';
2
import Header from './components/Header/Header';
3
import Counter from './components/Counter/Counter';
4
5
const App = () => (
6
<div>
7
<Header />
8
<Counter />
9
</div>
10
);
11
12
export default App;

As you can see, we have imported the Header Component. We have added the Header Component to the App Component.

Explanation:

  • import Header from './components/Header/Header' - import the Header Component
  • <Header /> - add the Header Component to the App Component

Step 11: Run the application

We will run the application.

Terminal window
yarn dev

Redux Toolkit Counter with Header

As you can see, we have a counter. We can increment the counter. We can decrement the counter. We can increment the counter by 5. We have a header with the count value.

Source Code

You can find the source code for this tutorial on GitHub. You can clone the repository and run the application.

Terminal window
# Clone the repository
git clone https://github.com/MKAbuMattar/react-with-redux-toolkit.git
# Go inside the directory
cd react-with-redux-toolkit
# Install dependencies
yarn install
# Run the application
yarn dev

Conclusion

In this article, we learned how to establish a Redux store using the Redux Toolkit. A Redux slice can now be made, as we have learned. We now know how to take an action. We now know how to build reducers. We now know how to build a Redux store. The Redux store may now be added to the App Component, as we learned how to do. We now know how to add the Counter Component to the App Component. Accessing the count value in other components is something we now know how to do. We have learned how to add the Header Component to the App Component.

Resources

Related Posts

Check out some of our other posts

Setup Nextjs Tailwind CSS Styled Components with TypeScript

Setup Nextjs Tailwind CSS Styled Components with TypeScript

Introduction In this post, we will setup Nextjs Tailwind CSS Styled Components with TypeScript, and we will use the following tools:Nextjs Tailwind CSS Styled Components TypeScript

read more
Building a Customizable Image Slider in React Using Hooks, SCSS, and TypeScript

Building a Customizable Image Slider in React Using Hooks, SCSS, and TypeScript

Introduction In this tutorial, we will be building a customizable image slider in React using hooks, SCSS, and TypeScript. An image slider is a common UI element used in web applications to displ

read more
Unlocking the Power of React Context API: Demystifying State Management

Unlocking the Power of React Context API: Demystifying State Management

Introduction In the ever-evolving realm of web development, the effective management of application state is a pivotal aspect that can either elevate or hinder your project's success. In this con

read more