Setting Up a Simple Counter App with Redux: A Step-by-Step Guide

Jakaria Masum - Aug 22 - - Dev Community

Introduction

Redux is a powerful state management library, but getting started with it can sometimes feel daunting, especially for beginners. In this guide, we'll walk through the process of setting up a simple counter app using Redux. By the end of this tutorial, you'll have a better understanding of how Redux works and how you can integrate it into your React projects.

Prerequisites

Before we dive into the setup, make sure you have the following installed:

  • Node.js (LTS version recommended)
  • npm or yarn
  • Basic knowledge of React

Step 1: Set Up the React Application

First, let's create a new React application using Vite. Open your terminal and run the following command:

npm create vite@latest counter-app -- --template react
cd counter-app
npm install
Enter fullscreen mode Exit fullscreen mode

This will create a new directory named counter-app with all the necessary files for a React app.

Step 2: Install Redux and React-Redux

Next, we need to install Redux and React-Redux, which provides the bindings to connect Redux with React.

npm install @reduxjs/toolkit react-redux
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the Counter Slice

Reducers in Redux are pure functions that take the current state and an action as arguments and return a new state. Let's create a reducer to handle our counter state.

In the redux folder, create a folder named features. Inside this create a file named counterSlice.ts:

import { createSlice, PayloadAction } from "@reduxjs/toolkit";

type TinitialState = {
  count: number;
};
const initialState: TinitialState = { count: 0 };
const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    increment: (state) => {
      state.count = state.count + 1;
    }, 
    decrement: (state) => {
      state.count = state.count - 1;
    }  },
});
export const {
  increment,
  decrement,
  } = counterSlice.actions;
export default counterSlice.reducer;
Enter fullscreen mode Exit fullscreen mode

Step 4: Create hook.ts inside src folder and put these lines. These are used for type-safety for the application

import { useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";

// Use throughout your app instead of plain useDispatch and useSelector
export const useAppDispatch = useDispatch.withTypes();
export const useAppSelector = useSelector.withTypes();

This allows use to use useAppDispatch and useAppSelector instead of useDispatch and useSelector respectively.

Step 5: Create middlewares.ts inside src folder to create customized Loggoer middlewares which allows to see our current action, previous action and next action in react devtools.

const Logger = (state) => (next) => (action) => {
  console.log("Current State: ", state.getState());
  console.log("Action", action);
  next(action);
  console.log("Next state", state.getState());
};

export default Logger;

Enter fullscreen mode Exit fullscreen mode

Step 6: Create the Redux Store

In Redux, the store is the central place where the entire state of your application is kept. Let’s create a simple store for our counter app.

Inside the src directory, create a new folder named redux. Inside this folder, create a file named store.ts:

import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "./features/counterSlice";
import Logger from "./middlewares";

export const store = configureStore({
  reducer: {
    counter: counterSlice,
  },
  middleware: (getDefaultMiddlewares) => getDefaultMiddlewares().concat(Logger),
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;
Enter fullscreen mode Exit fullscreen mode

This reducer handles two actions: INCREMENT and DECREMENT, which will increase or decrease the counter, respectively.

Step 6: Connect Redux to React

Now that we have our store, reducer, and actions set up, it's time to connect Redux to our React application. We'll do this using the Provider component from react-redux.

In the src directory, open the index.js file and wrap your App component with the Provider:

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

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Step 7: Create the Counter Component

Next, let's create a simple counter component that will display the counter value and buttons to increment and decrement it.

In the src directory, open the App.js file and replace its contents with the following:

import {
  decrement,
  increment} from "./redux/features/counterSlice";
import { useAppDispatch, useAppSelector } from "./redux/hooks";

function App() {
  const { count } = useAppSelector((state) => state.counter);
  const dispatch = useAppDispatch();
  return (
    <div className="h-screen w-full flex justify-center items-center bg-slate-50">
      <div className="border border-purple-500 flex p-24">
        <div
          onClick={() => dispatch(reset())}
          className="px-4 py-1 bg-purple-500 text-white cursor-pointer"
        >
          Reset
        </div>
        <button
          onClick={() => dispatch(increment())}
          className="bg-green-500 px-3 py-2 rounded-md  "
        >
          Increment
        </button>

        <button
          onClick={() => dispatch(decrement())}
          className="bg-red-500 px-3 py-2 rounded-md "
        >
          Decrement
        </button>
      </div>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Step 8: Run the Application

With everything set up, it's time to run the application and see the counter in action.

In your terminal, run:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:5173. You should see a simple counter with two buttons to increment and decrement the value.

. . . . . .
Terabox Video Player