 

JavaScript・4 min read・Posted on July 18, 2024

# A Comprehensive guide to integrate Redux Toolkit with React using counter example

 

 

 

 ![A Comprehensive guide to integrate Redux Toolkit with React using counter example](/sites/default/files/remediation-media/6698edf1bce8328419d8c790_A_Comprehensive_Guide_to_integrate_Redux_Toolkit_with_React_using_Counter_Example_JS_.avif) 

 



 

   Table of contents  - [What is Redux toolkit?](#what-is-redux-toolkit)
- [Setting Up](#setting-up)
- [Creating the counter slice](#creating-the-counter-slice)
- [Configuring the store](#configuring-the-store)
- [Creating the counter component](#creating-the-counter-component)
- [Adding the counter component to the app](#adding-the-counter-component-to-the-app)
- [Running the application](#running-the-application)
- [Conclusion](#conclusion)
 
  

 

Redux is a powerful tool for managing state in JavaScript applications, but it can be complex and verbose.Redux Toolkit – a library that simplifies Redux development with a set of tools and best practices.It has revolutionized state management in React applications by simplifying Redux logic and reducing boilerplate code.

In this blog post, we'll explore Redux Toolkit by building a simple counter application. We'll cover the essential concepts, provide a detailed code example, and explain each part step by step.

## What is Redux toolkit?

Redux Toolkit (RTK) is the official, recommended way to write Redux logic. It provides:

1. **Simple configuration:** Easy setup with pre-configured store and middleware.
2. **Reduced boilerplate:** Simplified syntax for actions and reducers.
3. **Powerful tools:** Built-in tools for common tasks like asynchronous logic , redux dev tools and immutability .

## Setting Up

First, let's set up a new React application with Redux Toolkit. If you haven't already, you'll need to install the necessary packages:

 ```
npx create-react-app redux-toolkit-counter
cd redux-toolkit-counter
npm install @reduxjs/toolkit react-redux
```

## Creating the counter slice

In Redux Toolkit, a slice is a collection of reducer logic and actions for a single feature of your app and managed independently. Let's create a counter slice using **createSlice** from redux toolkit.

**createSlice** is a higher-order function that takes an initial state, an object containing reducer functions, and a slice name. It automatically generates action creators and action types that match the reducers and state.

In Redux Toolkit, the **createSlice** method assists in creating a slice of the Redux store. This function aims to minimize the boilerplate code needed to add data to Redux in the standard manner. Internally, it utilizes **createAction** and **createReducer.**

**‍**

1. Create a new file **counterSlice.js** in the src folder:

**Step 1:** First, import the **createSlice** method from the Redux Toolkit library.

**Step 2 :**Use the **createSlice** method to define your slice.

**Step 3:** The **counterSlice** created contains all the necessary values to set up a reducer. Now, we need to export the actions and the reducer.

 ```
// src/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

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

export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
```

‍

**createSlice** examines all the functions defined in the reducers field and generates an action creator(which returns an action object ) for each case, using the name of the slice and name of reducer object keys as the action type.

In the code above, the **increment** reducer becomes an action type of **counter/increment**, and the **increment()** action creator will return an action with that type.Similarly for **decrement** as **counter/decrement** and  **incrementByAmount** as  **counter/incrementByAmount.**

## Configuring the store

Next, we'll configure the Redux store to include our counter slice.

1. Create a new file **store.js** in the **src** folder:

 ```
// src/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';

const store = configureStore({
  reducer: {
    counter: counterReducer
  }
});

export default store;
```

**configureStore({})** wraps **createStore()** to streamline the configuration process. createStore() is a Redux store that maintains the entire state tree of your app.

1. Update **index.js** to provide the store to your React application:

Now we need to connect our store to the app.This can be done by **Provider** from react-redux.

The **&lt;Provider&gt;** component provides the Redux store to any nested components that need access to it.

Because any React component in a React Redux app can connect to the store, most applications place a **&lt;Provider&gt;** at the top level, encapsulating the entire app's component tree.

The **&lt;Provider&gt;** component accepts store as a prop.

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

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

## Creating the counter component

Now, let's create a **Counter** component that interacts with our Redux state.

1. Create a new file Counter.js in the src folder:

Now, we should utilize the React hooks **useSelector** to retrieve the state and **useDispatch** to dispatch the actions created in the slice.

**useSelector** is a React Redux hook designed for components to retrieve and access data from the Redux store. It subscribes the component to the Redux store, ensuring that any updates in the state trigger a re-render of the component to reflect these changes. This hook returns the selected data from the Redux store, allowing you to incorporate it directly within your component.

**useDispatch** is a React Redux hook that enables components to dispatch actions to the Redux store. It provides a reference to the dispatch function of the Redux store, allowing components to initiate state changes.

 ```
// src/Counter.js
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from './counterSlice';

const Counter = () => {
  const count = useSelector(state => state.counter.value);
  const dispatch = useDispatch();
  const [incrementAmount, setIncrementAmount] = useState(0);

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
      <input
        type="number"
        value={incrementAmount}
        onChange={(e) => setIncrementAmount(Number(e.target.value))}
      />
      <button onClick={() => dispatch(incrementByAmount(incrementAmount))}>
        Increment by Amount
      </button>
    </div>
  );
};

export default Counter;
```

## Adding the counter component to the app

Finally, we'll add the **Counter** component to our **App** component.

1. Update **App.js** to include the **Counter** component:

 ```
// src/App.js
import React from 'react';
import Counter from './Counter';

const App = () => {
  return (
    <div className="App">
      <Counter />
    </div>
  );
}

export default App;
```

## Running the application

Now, you can start your application and see Redux Toolkit in action:

 ```
npm start
```

Navigate to **http://localhost:3000** in your browser, and you should see your counter application working. You can increment, decrement, and increment by a specified amount.

## Conclusion

Redux Toolkit makes managing state in your React applications easier and more efficient. By reducing boilerplate and providing powerful tools out of the box, it simplifies the process of writing Redux logic. In this blog post, we built a simple counter application using Redux Toolkit, demonstrating its core features and benefits.

Feel free to extend this example and explore other features of Redux Toolkit, such as asynchronous logic with **createAsyncThunk** and more advanced use cases. Happy coding!

‍

 



Written by

Shruthi Kathula

Engineer-JavaScript

 

 

 

 

 

 

 ## We'd love to talk about your business objectives

 [ Contact Us  ](/contact)