So.. You want to use Redux toolkit


Hello everyone. This is a quick guide to setting up redux-toolkit to use it right away for all the amazing things it lets you do.
First some background, redux-toolkit is meant to reduce the boilerplate in writing redux logic, as everyone used to complain that redux is too complicated. Redux is a state management library for using global states across your applications, which is useful when you have to share data between multiple components. Sending data from one component to another might sometimes involve passing it through multiple components that don’t even use it. To not do this, we use redux. Redux toolkit is just an easier way to write redux with some extra functionalities.
In this article we discuss how to set up and use redux toolkit to store and use a global state in react.
Before we get started, I’m not a pro at redux either. If you want a better guide please check out the official docs.
Consider this example of a isLoggedIn
state in a regular Login.jsx component
const Login = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return(
<>
<button onClick={setIsLoggedIn(true)} >Login</button>
<button onClick={setIsLoggedIn(false)} >Logout</button>
{isLoggedIn ? <h1>Welcome to the platform</h1> : <h1>Please login</h1>}
</>
);
}
To share this isLoggedIn
state with other components to render pages based on the login status we usually pass the state through props to other states. What if the isLoggedIn
state needs to be used in almost every other page? You can still use a global state by just defining the state in the App.jsx
and pass the state down to every page that is routed in the App.jsx
file, like I used to before I came across redux (Dumb right? I know). But the problem becomes obvious to notice when you start having multiple such global states that you are passing down to every component as a prop or when you have to pass the same state to a component→ its child → its child → its child and so on. This is where redux comes in, it provides a centralized “store” where you can manage store such global states and use them in any component easily.
To set up redux toolkit in your existing project use the following command:
npm install @reduxjs/toolkit react-redux
Mentioning react-redux install the react binding for redux. It can be skipped if you’re not working with react.
Before moving on to setting up redux, let us talk about all the important things redux provides for making this data/state management easier.
Store - A centralized store for storing and managing global state
Actions - JavaScript objects that tell redux what changes should be done
Reducers - Functions that change the state and return a new state
Dispatch - A function to send a change (action) to redux store
Selector - A function that fetches any information from the redux store
With that in mind let us now try create store. After installing redux-toolkit, create a new folder to host your store. Create a file store.js and a authSlice.js
In the authSlice.js file we create reducers and generate actions and export them as shown below.
First we define our initial state, createSlice
function is used to create the authSlice. We need to mention a name, initial state and define reducers for each slice. Here we have 2 reducers login and logout, both are functions that take a state as an input and change it. In the end we generate actions using .actions
and export them. The store listens to dispatched (more about it later) actions to update state.
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
isLoggedIn: false,
};
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
login: (state) => {
state.isLoggedIn = true;
},
logout: (state) => {
state.isLoggedIn = false;
},
},
});
export const { login, logout } = authSlice.actions;
export default authSlice.reducer;
Each slice can have multiple reducers, and actions. Once all our slices are created, we can create a store to save them. With redux toolkit a store can be created automatically using configureStore
and we export the store.
store.js
import { configureStore } from "@reduxjs/toolkit";
import authReducer from "../Slices/authSlice";
const store = configureStore({
reducer: {
auth: authReducer,
},
});
export default store;
In the main.jsx (or App.jsx) we wrap the entire App component with a provider from redux, and pass the store.
import App from './App.jsx'
import { Provider } from "react-redux";
import store from "./redux/store";
createRoot(document.getElementById('root')).render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>,
)
Once this is done, we can use dispatch any actions we want from any component where it is required, we can also select any state we want using selectors. First let us see how to dispatch an action
In our Login.jsx
earlier we can now use the useDispatch()
provided by redux toolkit to change the state from our component
import { useDispatch } from "react-redux";
import { login } from "./redux/authSlice";
const Login = () => {
// const [isLoggedIn, setIsLoggedIn] = useState(false);
const dispatch = useDispatch();
const handleLogin = (value) => {
if(value){
dispatch(login(true));
}else{
dispatch(logout(true));
}
}
return(
<>
<button onClick={() => handleLogin(true)} >Login</button>
<button onClick={() => handleLogin(false)} >Logout</button>
</>
);
}
export default Login;
The store listens to the actions dispatched and updates the states.
To retrieve the state from the store we can use the useSelector()
provided by the redux toolkit. Here’s an example of how to use selectors.
The selector in this example fetches the isLoggedIn
state that is defined in the authSlice and uses it to conditionally render the message.
import { useDispatch, useSelector } from "react-redux";
import { login } from "./redux/authSlice";
const Login = () => {
// const [isLoggedIn, setIsLoggedIn] = useState(false);
const dispatch = useDispatch();
const handleLogin = (value) => {
if(value){
dispatch(login(true));
}else{
dispatch(logout(true));
}
}
const isLoggedIn = useSelector((state) => state.auth.isLoggedIn);
return(
<>
<button onClick={() => handleLogin(true)} >Login</button>
<button onClick={() => handleLogin(false)} >Logout</button>
{isLoggedIn ? <h1>Welcome to the platform</h1> : <h1>Please login</h1>}
</>
);
}
export default Login;
And that’s how you set up redux in your react project and make your life simpler (or more complex). If you wish to know more about redux, these are my recommended resources
- Piyush Garg - Redux toolkit
- Chai aur Code - Redux toolkit crash course
Try to implementing redux toolkit in your next project and share how it goes in the comments :)
Subscribe to my newsletter
Read articles from Bhavitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
