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’;const counterSlice = createSlice({
name: ‘counter’,
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
},
});export const { increment, decrement } = counterSlice.actions;
export const counterReducer = counterSlice.reducer;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’;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 the Counter component:
import React from ‘react’;
import { Provider } from ‘react-redux’;
import Counter from ‘./Counter’;
import { store } from ‘./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.
Source: hashnode.com