"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Complete Redux toolkit (Part-1)

Complete Redux toolkit (Part-1)

Published on 2024-10-31
Browse:149

Complete Redux toolkit (Part-1)

Purpose of Redux Toolkit

We already know redux is a powerful state management library for our JavaScript applications, specially when working with React.
But working with redux is hard due to its heavy code for setting up redux. Which makes it hard to maintain and debug. Thats where Redux Toolkit comes to help.
Problems Redux toolkit solve

  • Setting up store is too complecated.
  • Adding many package to work with redux e.g., Middleware , tools.
  • Redux needs too much code to setup

Redux toolkit is the official and recommended way to write redux logic.It provide a set of tools to simplify the development, reduce boilerplate code which help make scalability and maintainable application.

Key benefits of Redux Toolkit:

  1. Less boilerplate code: Remove the need for action creators and constants.
  2. Simplified store setup: Provides a single API to configure the store with sensible defaults.
  3. Built-in support for immutability and DevTools: Automatically enables Redux DevTools and integrates with Immer for immutability.
  4. Better TypeScript support: Provides better typings and integrates well with TypeScript.

We can use redux toolkit with any javascript library so we setup redux toolkit with react.

Setting Up Redux Toolkit in a React Application

Step 1: Create a New React Project

First, let's create a new React application. You can use create-react-app or Vite for this purpose. We'll use create-react-app here for simplicity.

npx create-react-app redux-toolkit-example
cd redux-toolkit-example

Step 2: Install Redux Toolkit and React-Redux

Next, install the necessary packages: @reduxjs/toolkit and react-redux.

npm install @reduxjs/toolkit react-redux
  1. Understanding Slices and Reducers

A slice is a collection of Redux reducer logic and actions for a specific feature of your application. Redux Toolkit provides the createSlice function to help create a slice of state with minimal boilerplate.

Step 1: Create a Slice
Let's create a simple counter slice. Create a new file named counterSlice.js inside a features/counter directory:

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

const initialState = {
  value: 0,
};

const counterSlice = createSlice({
  name: 'counter',
  initialState,
  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;

Here, we define a slice named counter with an initial state and three reducers (increment, decrement, and incrementByAmount). The createSlice function automatically generates action creators for each reducer function.

  1. Configuring the Redux Store

Now that we have our slice, let's configure the Redux store. Redux Toolkit provides a configureStore function that sets up the store with good defaults.

Step 1: Create a Store
Create a store.js file inside a app directory:

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

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

export default store;

Step 2: Provide the Store to Your App
Wrap your React application in a component from react-redux and pass it the store. Update the index.js file:

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

ReactDOM.render(
  ,
  document.getElementById('root')
);
  1. Connecting Components to the Store

To interact with the Redux store, use the useSelector and useDispatch hooks provided by react-redux.
Step 1: Access State with useSelector
Use the useSelector hook to access state from the store

// src/features/counter/Counter.js
import React 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();

  return (
    

{count}

); }; export default Counter;

Step 2: Use Counter Component in Your App
Import and use the Counter component in your main App component:

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

function App() {
  return (
    
); } export default App;
  1. Conclusion and Next Steps

In this part, we covered the basics of setting up Redux Toolkit in a React application, including creating slices, configuring the store, and connecting components to the Redux store using hooks. In the next part, we will dive deeper into handling asynchronous logic with createAsyncThunk to fetch data from APIs and manage different loading states.

Stay tuned for Part 2: Advanced Redux Toolkit - Async Logic with createAsyncThunk!

Release Statement This article is reproduced at: https://dev.to/abhishekpanwarrr/complete-redux-toolkit-part-1-58ph?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3