Redux Toolkit Modern State Management
Learn modern Redux with Redux Toolkit for simpler state management.
Why Redux Toolkit?
Redux Toolkit simplifies Redux significantly. Reduces boilerplate, includes best practices by default, and handles immutable updates automatically.
Setting Up Store
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
export const store = configureStore({
reducer: {
counter: counterReducer,
},
});
Creating a Slice
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { state.value += 1; },
decrement: (state) => { state.value -= 1; },
addBy: (state, action) => { state.value += action.payload; },
},
});
export const { increment, decrement, addBy } = counterSlice.actions;
export default counterSlice.reducer;
Using in Components
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './counterSlice';
function Counter() {
const count = useSelector(state => state.counter.value);
const dispatch = useDispatch();
return (
{count}
);
}
Conclusion
Redux Toolkit is the modern way to use Redux. createSlice dramatically reduces the code needed.