In this article, we will cover step by step manner how you can implement redux toolkit in your react project.
Blog
npm install --save react-redux @reduxjs/toolkit
import { configureStore } from "@reduxjs/toolkit";
export const store = configureStore({
reducer: {},
});
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>
);
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;
import { configureStore } from "@reduxjs/toolkit";import counterRedcuer from "../features/counter/counterSlice";export const store = configureStore({ reducer: { counter: counterRedcuer },});
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> </> );}
Lets revise all the steps again –
Hope you guys found the article helpful.
Copyright ©2024 Preplaced.in
Preplaced Education Private Limited
Ibblur Village, Bangalore - 560103
GSTIN- 29AAKCP9555E1ZV