Redux Toolkit
Dashboard
Topic 9/10
Home › React › Redux Toolkit

🏪 Redux Toolkit

Centralized state store, slices (createSlice), configureStore, useSelector, and useDispatch.

What is Redux Toolkit (RTK)?

Redux Toolkit is the official, modern toolset for efficient Redux state management. It eliminates boilerplate code.

Creating Slices with createSlice

A slice bundles initial state, reducers, and action creators together.

counterSlice.js JavaScript
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;

Using Store Data in React Components

Extract state with `useSelector` and dispatch actions with `useDispatch`.

CounterApp.jsx JSX
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './counterSlice';

export function CounterApp() {
  const count = useSelector(state => state.counter.value);
  const dispatch = useDispatch();

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => dispatch(increment())}>+1</button>
      <button onClick={() => dispatch(decrement())}>-1</button>
    </div>
  );
}