Complete Redux toolkit (Part-1)

abhishekpanwarrr

Abhishek Panwar

Posted on September 8, 2024

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
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Redux Toolkit and React-Redux

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

npm install @reduxjs/toolkit react-redux
Enter fullscreen mode Exit fullscreen mode
  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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode
  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 (
    <div>
      <h1>{count}</h1>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
      <button onClick={() => dispatch(incrementByAmount(5))}>Increment by 5</button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

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 (
    <div className="App">
      <Counter />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
  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!

💖 💪 🙅 🚩
abhishekpanwarrr
Abhishek Panwar

Posted on September 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Complete Redux toolkit (Part-1)
javascript Complete Redux toolkit (Part-1)

September 8, 2024

Redux
javascript Redux

February 25, 2022