Creating boilerplate code for your Redux applications is something you may be sick of doing. Do you wish that managing the state of your application were easier and more effective? You’ve found it!
The Redux Toolkit is a potent library that has completely changed how we build Redux code, and we’ll go on a fascinating exploration of it in this post.
New to Redux? Click Here
Chapter 1: The Annoying Boilerplate Curse
Once upon a time, in the land of Redux, developers faced a great challenge: the infamous boilerplate curse. To wield the power of Redux, they had to write countless lines of code just to set up a simple store, define actions, and define reducers.
It was a tedious and error-prone process, leaving developers longing for a more elegant solution.
Chapter 2: A Whisper from the Redux Gods
One fateful day, a whisper spread through the developer community. The Redux gods had bestowed a gift upon the world — a mighty library called Redux Toolkit. It promised to vanquish the dreaded boilerplate curse and make Redux development a breeze. Intrigued, developers set out on a quest to uncover its secrets.
Chapter 3: The Art of Installation
To begin our journey, we must first summon Redux Toolkit into our project. Open your terminal and invoke the magical incantation:
npm install @reduxjs/toolkit or yarn add @reduxjs/toolkit
Chapter 4: The Sacred Store
Now that Redux Toolkit has graced our project, we can create the heart of our application — the Redux Store.
import { configureStore } from "@reduxjs/toolkit";
export const store = configureStore({
// Configure your slices, middleware, and other options here
});
export type RootState = ReturnType<typeof store.getState>;
Behold! The store is ready.
Chapter 5: The Marvelous Slices
In the realm of Redux, slices represent portions of the application’s state and contain reducers and actions relevant to them.
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
interface initInterface {
user: any;
}
const initialState: initInterface = {
user: {}
};
export const userSlice = createSlice({
name: "users",
initialState,
reducers: {
getGitUser: (state, action: PayloadAction<any>) => {
state.user = action.payload;
}
}
});
export const { getGitUser } = userSlice.actions;
export default userSlice.reducer;
Now call forth the slice from the Sacred store.
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "./reducers/userSlice";
export const store = configureStore({
reducer: {
git: userReducer
}
});
export type RootState = ReturnType<typeof store.getState>;
You have successfully set up the Redux Store, now let’s provide the store to React.
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import { store } from "../redux/store";
const rootElement = document.getElementById("root")!;
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
Chapter 6: Dispatch and Extract
Now that we have assembled our Redux store and defined slices, it’s time to unleash the true power of the Redux Toolkit. In this chapter, we will learn the art of dispatching reducers and extracting data from the state.
The Enchanting dispatch
To make our Redux application come alive, we need to dispatch actions to trigger the reducers and update the state.
For better understanding, I have considered the example of fetching user data from GitHub API.
import axios from "axios";
export const getDataAPI =async ()=>{
return await axios.get("https://api.github.com/users/idebenone");
}
import { useDispatch} from "react-redux";
import { getDataAPI } from "../utils/api";
import { getGitUser } from "../redux/reducers/userSlice";
const fetchData = async () => {
try {
const res = await getDataAPI();
dispatch(getGitUser(res.data)); //dispatching the response recieved from API
} catch (error) {
console.error("Error fetching data:", error);
}
};
The Art of Extraction
We often need to extract data from the state to display it in our components or perform calculations. Redux Toolkit equips us with the means to accomplish this with grace.
import { useSelector } from "react-redux";
import { RootState } from "../redux/store";
const git = useSelector((state: RootState) => state.git.user);
Through the useSelector hook, we can pluck specific data from the state. In this example, we extract the git slice from the state. We can use this value anywhere in the component.
Here is the complete code:
import { useEffect } from "react";
import "./styles.css";
import { useDispatch, useSelector } from "react-redux";
import { getDataAPI } from "../utils/api";
import { getGitUser } from "../redux/reducers/userSlice";
import { RootState } from "../redux/store";
export default function App() {
const git = useSelector((state: RootState) => state.git.user);
const dispatch = useDispatch();
useEffect(() => {
const fetchData = async () => {
try {
const res = await getDataAPI();
dispatch(getGitUser(res.data));
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
}, [dispatch]);
return (
<div className="App">
<h1>Redux Exmaple</h1>
<p>with GitHub API</p>
<div
style={{
display: "flex",
flexDirection: "column",
height: "60vh",
alignItems: "center",
justifyContent: "center"
}}
>
<h3>GitHub User Information</h3>
<div
style={{
display: "flex",
flexDirection: "row",
gap: "2rem",
justifyContent: "center"
}}
>
<p>
<img src={git.avatar_url} alt="" style={{ height: "100px" }} />
</p>
<div style={{ display: "flex", flexDirection: "column" }}>
<h2>{git.name}</h2>
<button
style={{
padding: "1rem",
backgroundColor: "black",
border: "none"
}}
>
<a
style={{ textDecoration: "none", color: "white" }}
href={git.html_url}
target="_blank"
rel="noreferrer"
>
Profile Link
</a>
</button>
</div>
</div>
</div>
</div>
);
}
Congratulations, brave developer! You have triumphed over the boilerplate curse with Redux Toolkit. Happy Coding