React - Redux Toolkit
Using Redux Toolkit to simplify Redux code
Redux Toolkit is the official, recommended way to write Redux logic. It provides a set of tools and best practices that simplify Redux development and improve code quality. This tutorial covers how to use Redux Toolkit to simplify Redux code in your React applications.
Key Points:
- Redux Toolkit provides a set of tools and best practices for writing Redux logic.
- It includes utilities for creating slices, reducers, actions, and the Redux store.
- Redux Toolkit simplifies Redux code, reducing boilerplate and improving code readability.
Installing Redux Toolkit
First, install Redux Toolkit and React-Redux using npm or yarn:
npm install @reduxjs/toolkit react-redux
# or
yarn add @reduxjs/toolkit react-redux
Creating a Slice
A slice is a collection of Redux reducer logic and actions for a single feature of your app. Use the createSlice
function to define a slice.
// Creating a slice
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { count: 0 },
reducers: {
increment: state => { state.count += 1; },
decrement: state => { state.count -= 1; }
}
});
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
Configuring the Store
Use the configureStore
function to create the Redux store and automatically combine your slices.
// Configuring the store
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
const store = configureStore({
reducer: {
counter: counterReducer
}
});
export default store;
Connecting Redux to React
Use the Provider
component from React-Redux to pass the Redux store to your React components.
// Connecting Redux to React
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')
);
Using useSelector and useDispatch
The useSelector
hook allows you to extract data from the Redux store state, and the useDispatch
hook gives you access to the dispatch
function.
// Using useSelector and useDispatch
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './counterSlice';
function Counter() {
const count = useSelector(state => state.counter.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
export default Counter;
Creating Async Thunks
Redux Toolkit includes createAsyncThunk
for handling asynchronous logic. It generates pending, fulfilled, and rejected action types automatically.
// Creating async thunks
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
export const fetchData = createAsyncThunk(
'data/fetchData',
async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
}
);
const dataSlice = createSlice({
name: 'data',
initialState: { data: null, status: 'idle' },
extraReducers: builder => {
builder
.addCase(fetchData.pending, state => { state.status = 'loading'; })
.addCase(fetchData.fulfilled, (state, action) => {
state.status = 'succeeded';
state.data = action.payload;
})
.addCase(fetchData.rejected, state => { state.status = 'failed'; });
}
});
export default dataSlice.reducer;
Summary
In this tutorial, you learned how to use Redux Toolkit to simplify Redux code in your React applications. Redux Toolkit provides tools and best practices for writing Redux logic, including utilities for creating slices, reducers, actions, and the Redux store. You learned about creating a slice, configuring the store, connecting Redux to React, using the useSelector
and useDispatch
hooks, and creating async thunks. Using Redux Toolkit simplifies Redux development, reduces boilerplate, and improves code readability.