Clue Mediator

How to set up and use Redux Toolkit with React-Redux

๐Ÿ“…December 1, 2022
๐Ÿ—ReactJS

Today, we will show you how to set up and use Redux Toolkit with React-Redux. You can improve your Redux code by using Redux Toolkit.

Redux Toolkit allows us to write "mutating" logic in reducers. It doesn't actually mutate the state because it uses the Immer library, which detects changes to a "draft state" and produces a brand new immutable state based off those changes

The Redux Toolkit package is meant to serve as the industry standard for writing Redux logic. It was initially developed to help respond to three prevalent worries regarding Redux:

  • Redux store configuration is too difficult.
  • We need to add a lot of packages for Redux to do any useful functions.
  • Too much boilerplate code is required by Redux.

Letโ€™s start with a simple example where we will use the Redux Toolkit to handle the counter in store.

Demo Application

How to set up and use Redux Toolkit with React-Redux - Clue Mediator

How to set up and use Redux Toolkit with React-Redux - Clue Mediator

Set up and use Redux Toolkit with React-Redux

  1. Create a react app
  2. Install dependencies
  3. Create a redux state slice
  4. Create a redux store and add slice reducer to store
  5. Provide redux store to react
  6. Add redux state and actions in react component
  7. Output

1. Create a react app

First, Create a react application using `create-react-app`. Run the following command to create an application.

npx create-react-app redux-toolkit-example

We will refer the following project structure to create an example.

  • redux-toolkit-example

    • node_modules

    • public

      • index.html
    • src

      • store

        • counterSlice.js
        • index.js
      • App.js

      • index.css

      • index.js

    • package-lock.json

    • package.json

    • README.md

2. Install dependencies

Add the Redux Toolkit and React-Redux packages to your project. Run the following command to install the packages.

npm i @reduxjs/toolkit react-redux

You may see the following versions in the package.json file.

react

^18.2.0

@reduxjs/toolkit

^1.9.1

react-redux

^8.0.5

3. Create a redux state slice

Add a new file named `src/store/counterSlice.js`. Import the `createSlice` API from Redux Toolkit into that file.

The `createSlice` API requires a string name, an initial value, and reducer functions to update the state. Once a slice is created, we have to export the reducer function for the whole slice.

src/store/counterSlice.js

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  count: 0,
}

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

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions

export default counterSlice.reducer

Here, we have created three functions increment, decrement, and incrementByAmount.

4. Create a redux store and add slice reducer to store

Now, create a redux store file named `src/store/index.js` and need to import the reducer function from the counter slice.

src/store/index.js

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

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

Similarly, we can import multiple reducer in the reducer object.

5. Provide redux store to react

Once the store has been created, we can make it accessible to our React components by enclosing our application in a React-Redux `<Provider>` in `src/store/index.js`.

src/index.js

import React from 'react';
import ReactDOM from 'react-dom/client';

import './index.css';
import App from './App';

import { Provider } from 'react-redux'
import { store } from './store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <provider store={store}>
    <app>
  </app></provider>
);

6. Add redux state and actions in react component

React components can now communicate with the Redux store using the React-Redux hooks. Using `useSelector`, we can get data from the store, and `useDispatch`, we can dispatch actions.

In this component, we will increment/decrement the counter in the Redux store.

src/App.js

import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { decrement, increment, incrementByAmount } from './store/counterSlice'

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

  return (
    <div>
      <h4>Set up and use Redux Toolkit with React-Redux - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4>
      <button onclick="{()" ==""> dispatch(increment())}>Increment</button>
      <button onclick="{()" ==""> dispatch(incrementByAmount(3))}>Increment +3</button>
      <span class="counter">{count}</span>
      <button onclick="{()" ==""> dispatch(decrement())}>Decrement</button>
    </div>
  )
}

export default App;

7. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚

Demo & Source Code

GitHub Repository StackBlitz Project