How to Use React Redux-Toolkit: A Comprehensive Example
Here's a simple example of using the React Redux Toolkit to manage the state in a React application:
Let's assume we want to create a simple counter application.
First, make sure you have a React project set up.
Install Redux Toolkit:
npm install @reduxjs/toolkit react-redux
Create a Redux store with Redux Toolkit:
Create a file named
store.js
:import { configureStore, createSlice } from '@reduxjs/toolkit'; // Define a slice with initial state and reducer const counterSlice = createSlice({ name: 'counter', initialState: { value: 0, }, reducers: { increment: (state) => { state.value += 1; }, decrement: (state) => { state.value -= 1; }, }, }); // Extract the actions and reducer from the slice export const { increment, decrement } = counterSlice.actions; export const counterReducer = counterSlice.reducer; // Create the Redux store export const store = configureStore({ reducer: { counter: counterReducer, }, });
Create a React component to display the counter:
Create a file named
Counter.js
:import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { increment, decrement } from './store'; // Import actions const Counter = () => { const count = useSelector((state) => state.counter.value); const dispatch = useDispatch(); return ( <div> <h1>Counter: {count}</h1> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> ); }; export default Counter;
Update your
App.js
to include theCounter
component:import React from 'react'; import { Provider } from 'react-redux'; import Counter from './Counter'; import { store } from './store'; // Import the Redux store const App = () => { return ( <Provider store={store}> <div> <h1>React Redux Toolkit Counter App</h1> <Counter /> </div> </Provider> ); }; export default App;
When you run your React application, you should see a counter that goes up and down when you click the buttons. This example shows how to use Redux Toolkit's createSlice
function to set up a part of the state with reducers and actions. It also explains how to use useSelector
and useDispatch
hooks to work with the Redux store in React components.