Add Redux Toolkit to your react project ?
In this article, we will cover step by step manner how you can implement redux… Expert Engineering career growth tips from industry mentors at Preplaced.
Step 1 - Install package
npm install --save react-redux @reduxjs/toolkitStep 2 - Create a global store
import { configureStore } from "@reduxjs/toolkit";
export const store = configureStore({
reducer: {},
});
Step 3 - Providing store to complete react app
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { store } from "./app/store";
import { Provider } from "react-redux";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store}>
<App />
</Provider>
);Step 4 – Now lets create a slice
import { createSlice } from "@reduxjs/toolkit";const initialState = { value: 0 };export const counterSlice = createSlice({ name: "counter", initialState, reducers: { increment: (state) => { state.value = state.value + 1; }, decrement: (state) => { state.value = state.value - 1; }, incrementByValue: (state, action) => { state.value = state.value + action.payload; }, incrementByTypedValue: (state, action) => { state.value = state.value + action.payload; }, },});export const { increment, decrement } = counterSlice.actions;export default counterSlice.reducer;Step 5 – Add Slice Reducers to the Store
import { configureStore } from "@reduxjs/toolkit";import counterRedcuer from "../features/counter/counterSlice";export const store = configureStore({ reducer: { counter: counterRedcuer },});Step 6 – Implementing useSelector and useDispatch in React Components
import React from "react";import { useSelector, useDispatch } from "react-redux";import { decrement, increment } from "../features/counter/counterSlice";export default function Counter() { const count = useSelector((c) => c.counter.value); const dispatch = useDispatch(); return ( <> <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", width: "40%", alignItems: "center", }} > <button onClick={() => dispatch(increment())}>Increment</button> <span>{count}</span> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> </> );}Conclusion
Lets revise all the steps again –
- Step 1 – Install the redux and react-redux package
- Step 2 – Create a store
- Step 3 – Providing store globally
- Step 4 – Creating slices (i.e reducers) , where all the major logics are performed
- Step 5 - Add Slice to reducer
- Step 6 – Receiving action from UI (using useDispatch hook) and receiving data from global store to fronted (using useSelector hook)
Hope you guys found the article helpful.
Frequently Asked Questions
Explore our complete guide
Software Engineering Career RoadmapFrom junior developer to engineering manager — guides, experiences, and advice from senior engineers on building a long-term tech career.