How to manage global state with Redux Toolkit in React
· Category: React
Short answer
Redux Toolkit (RTK) simplifies Redux by providing utilities like createSlice for reducer logic and configureStore for setup. React-Redux hooks connect components to the store.
Steps
- Create a slice with
createSlice, defining initial state, reducers, and generated actions. - Configure the store with
configureStore. - Provide the store at the app root with
<Provider>. - Use
useSelectorto read state anduseDispatchto dispatch actions.
Example
import { createSlice, configureStore } from '@reduxjs/toolkit';
import { Provider, useSelector, useDispatch } from 'react-redux';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { state.value += 1; },
},
});
const store = configureStore({ reducer: { counter: counterSlice.reducer } });
function Counter() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return <button onClick={() => dispatch(counterSlice.actions.increment())}>{count}</button>;
}
Tips
- RTK uses Immer internally, so you can write "mutating" logic safely.
- For complex async flows, use
createAsyncThunk. - Consider if your app truly needs Redux; Context or Zustand may be sufficient for small to medium apps.