• Home
  • Blog
  • Redux Toolkit Tutorial : Building a Simple Counter App

In this tutorial, we are going to learn how to create a basic counter app using Redux Toolkit for state management in a React application. Whether you’re new to Redux or want to explore the simplicity and power of Redux Toolkit, this step-by-step guide will walk you through the process of building a simple counter app with ease

Prerequisites

Before you begin, make sure you have the following prerequisites:

  1. Node.js and npm (Node Package Manager) installed on your computer.
  2. A basic understanding of JavaScript and React.

Step 1: Setting Up the React Application

Start by creating a new React application. Open your terminal and run the following commands:

npx create-react-app counter-app
cd counter-app
npm start

This will create a new React project named “counter-app” and start the development server.

Step 2: Installing Redux Toolkit

To use Redux Toolkit with React, you need to install two packages: redux and @reduxjs/toolkit. In your project directory, run:

npm install @reduxjs/toolkit

This will install Redux Toolkit and its dependencies.

Step 3: Creating the Counter Slice

In Redux Toolkit, a “slice” is a part of the Redux store that contains its own reducer and actions. Create a new file named counter.js in your project’s src directory. This file will define the counter slice:

// src/counter.js

import { createSlice } from '@reduxjs/toolkit';

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    count: 0,
  },
  reducers: {
    increment: (state) => {
      state.count += 1;
    },
    decrement: (state) => {
      state.count -= 1;
    },
    incrementByAmount: (state, action) => {
      state.count += action.payload;
    },
    decrementByAmount: (state, action) => {
      state.count -= action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount, decrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;

In this code, we define the initial state and create actions to increment, decrement, and modify the counter value.

Step 4: Configuring the Redux Store

In the same src directory, create a file named store.js to configure the Redux store:

// src/store.js

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counter';

export default configureStore({
  reducer: {
    counter: counterReducer,
  },
});

This file sets up the Redux store with our counterReducer.

Step 5: Building the Counter App Component

Open the src/App.js file and replace its contents with the following code:

// src/App.js

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  decrement,
  decrementByAmount,
  increment,
  incrementByAmount,
} from './redux/counter';
import './App.css';

function App() {
  const { count } = useSelector((state) => state.counter);
  const dispatch = useDispatch();

  return (
   <div className="App"> 
     <h1 className="counter-style">The count is:{count}</h1>
     <button className="button-style" onClick={() => dispatch(increment())}> Increment + 
     </button> 
     <button className="button-style" onClick={() => dispatch(decrement())}> Decrement - 
     </button> <button className="button-style" onClick={() => dispatch(incrementByAmount(10))} > Increment + by 10 
     </button> <button className="button-style" onClick={() => dispatch(decrementByAmount(10))} > Decrement - by 10 
     </button> 
   </div>
  );
}

export default App;

This component displays the counter value and provides buttons to increment, decrement, or modify it by a specific amount.

Step 6: Rendering the Application

In the src/index.js file, use the ReactDOM createRoot API to render the React application with Redux Toolkit:

// src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import App from './App';
import store from './store';

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>  
);

Step 7: Running the Application

Save your files and run the application with:

npm start

Visit http://localhost:3000 in your web browser to see your counter app in action. You can click the buttons to increment, decrement, or modify the counter value.

Congratulations! You’ve successfully built a simple counter app using Redux Toolkit for state management in a React application. This is a great starting point for learning how to use Redux Toolkit for more complex state management in your projects.

Understanding Redux Concepts

As we’ve built our counter app with Redux Toolkit, it’s essential to understand the core Redux concepts that underlie its functionality. These concepts play a vital role in how data flows in your application.

1. useSelector Hook

The useSelector hook is your window into the Redux store. It allows you to select specific pieces of data from the store’s state. In our counter app, we used it to access the count value. Here’s a quick recap of how it works:

 const { count } = useSelector((state) => state.counter);

You can select and retrieve data from the store based on your application’s state structure, making it available for use in your components.

2. useDispatch Hook

The useDispatch hook is your gateway to dispatching actions to the Redux store. Actions are functions that describe changes to the state. In our counter app, we dispatched actions like increment() or decrement():

const dispatch = useDispatch();
dispatch(increment());

It’s through useDispatch that you interact with the state, trigger changes, and keep your application in sync with user interactions.

3. Redux Store

The Redux store is the heart of your application’s state management. It acts as the central repository that holds your application’s state data. In the counter app, we used it to store the count value.

The Redux store is configured and set up with Redux Toolkit’s configureStore. It’s where all the state lives, making it accessible to any part of your application.

4. Reducers

Reducers are functions that specify how your application’s state should change in response to actions. They define how the state should be modified when an action is dispatched. In our counter app, the counterReducer is responsible for managing the state of the counter slice. It specifies how the count value should change when actions like increment() or decrement() are dispatched.

If you would  like to experiment with the entire code demonstrated in this tutorial, you’ll find it available in the redux-toolkit-counter GitHub repository for your access. For a live demo, you can check out the application here: Redux-Toolkit-Counter 

If you’re looking for expert assistance or guidance in developing React applications, whether it’s building a simple counter app or tackling more complex projects, our experienced team at SLC is here to help. Feel free to reach out to us for tailored solutions and professional support in bringing your software ideas to life.

Posted on October 11, 2023

Ishara Amarasekera

With a passion for cutting-edge tech, I'm a Scrum-certified Software Engineer & Mobile App Developer. My expertise spans native & cross-platform mobile and web app development. A skilled collaborator & proven communicator, I love crafting creative solutions for global clients.

We'd love to hear from you

Our friendly team would love to hear from you.





    You may also like

    We share all our learnings and innovations so you can use them, improve on them and let us know too...

    Basics of Docker for Software Development

    Introduction to Docker

    Docker is a containerization platform that enables developers to package applications along with their dependencies i...

    Read more

    Selenium IDE: Beginner’s Guide to Initiating Automation

    What is Selenium IDE ?

    Selenium IDE is a popular open-source tool for...

    Read more

    Figma Fundamentals: A Beginner’s Guide to Designing UI

    Designing websites or apps might seem hard, but with Figma, it's as easy as using a pencil! Whether you're making a cool ...

    Read more