State Management

Redux Toolkit Basics

Set up predictable global state with Redux Toolkit slices, store configuration, and async logic.

Why Redux Toolkit

Redux Toolkit is the recommended Redux approach because it reduces boilerplate and improves developer experience.

Install

bash
npm install @reduxjs/toolkit react-redux

Create a slice

tsx
import { 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 default counterSlice.reducer;

Setup store and provider

  • Configure store with reducers
  • Wrap app with <Provider store={store}>
  • Use useSelector and useDispatch hooks

Next, we will test React applications.