Redux Toolkit
Redux Toolkit (RTK) is the official, recommended way to write Redux logic. It simplifies common tasks like store setup, creating reducers, and immutable state updates.
Why use Redux Toolkit?
- Less Boilerplate: It provides functions that generate action creators and action types automatically.
- Immutable Updates: It uses Immer under the hood, allowing you to write "mutative" code that stays immutable.
- Standardized: It enforces best practices out of the box.
Creating a Slice
A Slice is a collection of Redux reducer logic and actions for a single feature.
JavaScript
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1;
},
},
});
export const { increment } = counterSlice.actions;
export default counterSlice.reducer; Using Redux in Components
We use useSelector to read data from the store and useDispatch to dispatch actions.
JavaScript
import { useSelector, useDispatch } from 'react-redux';
import { increment } from './counterSlice';
function Counter() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch(increment())}>
Count is {count}
</button>
);
} Note: While Redux is powerful, it's not always necessary. For simple state management, React's useState or Context API might be sufficient.