React Redux Toolkit
1. Install Redux Toolkit and React-Redux:
- npm install @reduxjs/toolkit react-redux
import { configureStore } from "@reduxjs/toolkit";import counterReducer from "./slices/counterSlice"; // Import your sliceexport const store = configureStore({reducer: {counter: counterReducer, // Add your reducers here},});export default store;
3. Create a Slice:
import { createSlice } from "@reduxjs/toolkit";const initialState = {count: 0,};const counterSlice = createSlice({name: "counter",initialState,reducers: {increment: (state) => {state.count += 1;},decrement: (state) => {state.count -= 1;},incrementByAmount: (state, action) => {state.count += action.payload;},},});export const { increment, decrement, incrementByAmount } = counterSlice.actions;export default counterSlice.reducer;
4. Provide the Store to the App:
import React from "react";import ReactDOM from "react-dom";import { Provider } from "react-redux";import App from "./App";import { store } from "./redux/store"; // Import storeReactDOM.render(<Provider store={store}><App /></Provider>,document.getElementById("root"));
5. Use Redux State and Actions in a Component:
import React from "react";import { useSelector, useDispatch } from "react-redux";import { increment, decrement, incrementByAmount } from "../redux/slices/counterSlice";const Counter = () => {const count = useSelector((state) => state.counter.count);const dispatch = useDispatch();return (<div><h2>Count: {count}</h2><button onClick={() => dispatch(increment())}>Increment</button><button onClick={() => dispatch(decrement())}>Decrement</button><button onClick={() => dispatch(incrementByAmount(5))}>Increment by 5</button></div>);};export default Counter;
Comments
Post a Comment