Quick Start with Redux Toolkit

date
Jul 20, 2024
slug
redux-toolkit
status
Published
tags
redux-toolkit
ReactJsDeveloper
redux
summary
Set up Redux Toolkit with React-Redux by installing the necessary packages, creating a store, providing it to your React app, and creating a state slice with reducers.
type
Post
 

Advantages of Redux Toolkit

Redux Toolkit offers several benefits that streamline Redux development:
  • Simplified Configuration: Minimizes boilerplate code for Redux store setup.
  • Built-in Best Practices: Incorporates utilities for out-of-the-box Redux best practices.
  • Enhanced Performance: Leverages Immer for efficient immutable updates.
  • Seamless DevTools Integration: Automatically configures Redux DevTools extension for easier debugging.
  • Efficient State Management: Utilizes createSlice API to simplify reducer and action creation.
  • Robust TypeScript Support: Ensures type safety with excellent TypeScript integration.
  • Streamlined Async Operations: Features createAsyncThunk for simplified async action handling.
These advantages position Redux Toolkit as an ideal choice for both novice and seasoned developers working with Redux.

What You'll Learn

  • Setting up and using Redux Toolkit with React-Redux.

Prerequisites

  • Understanding ES6 syntax and features.
  • Familiarity with React concepts: JSX, State, Function Components, Props, and Hooks.
  • Basic knowledge of Redux terminology and concepts.

Introduction

Welcome to the Redux Toolkit Quick Start Guide! This tutorial will give you a quick introduction to Redux Toolkit and show you how to set it up properly.

How to Use This Guide

This guide focuses on setting up a Redux application with Redux Toolkit and explaining the main APIs you'll use. For detailed explanations of Redux, how it works, and comprehensive examples, check out the tutorials linked in the "Tutorials Overview" page.
We'll assume you're using Redux Toolkit with React, but it can also be used with other UI layers. The examples follow the typical Create-React-App structure, but you can adapt them to your project's setup.
The Redux+JS template for Create-React-App comes pre-configured with this setup.

Quick Steps

1. Install Redux Toolkit and React-Redux

First, add Redux Toolkit and React-Redux to your project:
npm install @reduxjs/toolkit react-redux

2. Create a Redux Store

Next, create a file named src/app/store.js. Import the configureStore API from Redux Toolkit to set up an empty Redux store and export it:
import { configureStore } from '@reduxjs/toolkit' export const store = configureStore({ reducer: {}, })
This sets up a Redux store and configures the Redux DevTools extension for easier development.

3. Provide the Redux Store to React

To make the store available to your React components, wrap your application with a React-Redux <Provider> in src/index.js. Import the Redux store and wrap your <App> component, passing the store as a prop:
import React from 'react' import ReactDOM from 'react-dom' import './index.css' import App from './App' import { store } from './app/store' import { Provider } from 'react-redux' ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )

4. Create a Redux State Slice

Now, add a new file named src/features/counter/counterSlice.js. Import the createSlice API from Redux Toolkit. Creating a slice requires a string name to identify it, an initial state value, and one or more reducer functions to define how the state can be updated. Once the slice is created, export the generated Redux action creators and the reducer function for the whole slice:
import { createSlice } from '@reduxjs/toolkit' const initialState = { value: 0, } export 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
Redux Toolkit's createSlice and createReducer APIs use Immer internally, allowing you to write "mutating" update logic that becomes correct immutable updates.

5. Add Slice Reducers to the Store

Next, import the reducer function from the counter slice and add it to your store. By defining a field inside the reducer parameter, you tell the store to use this slice reducer function to handle all updates to that state:
import { configureStore } from '@reduxjs/toolkit' import counterReducer from '../features/counter/counterSlice' export const store = configureStore({ reducer: { counter: counterReducer, }, })

6. Use Redux State and Actions in React Components

Now you can use the React-Redux hooks to let React components interact with the Redux store. Use useSelector to read data from the store and useDispatch to dispatch actions. Create a src/features/counter/Counter.js file with a <Counter> component, then import that component into App.js and render it inside <App>:
import React from 'react' import { useSelector, useDispatch } from 'react-redux' import { decrement, increment } from './counterSlice' export function Counter() { const count = useSelector((state) => state.counter.value) const dispatch = useDispatch() return ( <div> <div> <button aria-label="Increment value" onClick={() => dispatch(increment())} > Increment </button> <span>{count}</span> <button aria-label="Decrement value" onClick={() => dispatch(decrement())} > Decrement </button> </div> </div> ) }
Now, whenever you click the "Increment" and "Decrement" buttons:
  • The corresponding Redux action will be dispatched to the store.
  • The counter slice reducer will process the actions and update its state.
  • The <Counter> component will receive the updated state value from the store and re-render with the new data.
By following these steps, you'll have a working Redux Toolkit setup integrated with React!
If you have any questions, please contact me.