Now it’s finally time to start coding with Redux Toolkit. In this lesson, we’ll learn:
createSlice()In Redux Toolkit, a slice represents a section of your application’s state.
Each Slice contains:
It’s called a slice because it represents a slice of the global state tree.
counterSlice → manages count
pokemonSlice → manages Pokémon list
userSlice → manages user profile
createSlice() — The Core of RTKRedux Toolkit provides a helper called createSlice() that lets us define:
Create a new folder:
src/features/counter/counterSlice.js
Then add:
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;
| Part | Meaning |
|---|---|
| name | Identifier for this piece of state |
| initialState | Default value for this slice |
| reducers | Functions that change the state |
| actions | Automatically generated based on reducer names |
Redux Toolkit uses Immer so we can write state.value += 1 directly (mutating syntax is allowed safely).
Create the store file:
src/store.js
import { configureStore } from "@reduxjs/toolkit";import counterReducer from "./features/counter/counterSlice";export const store = configureStore({reducer: {counter: counterReducer,},});
Open your main.jsx (Vite) or index.js (CRA):
import React from "react";import ReactDOM from "react-dom/client";import App from "./App";import { Provider } from "react-redux";import { store } from "./store";ReactDOM.createRoot(document.getElementById("root")).render(<Provider store={store}><App /></Provider>);
This gives the entire app access to the Redux store.
Open App.jsx and modify it:
import { useSelector, useDispatch } from "react-redux";import { increment, decrement } from "./features/counter/counterSlice";function App() {const count = useSelector((state) => state.counter.value);const dispatch = useDispatch();return (<div style={{ textAlign: "center", marginTop: "50px" }}><h1>Counter: {count}</h1><button onClick={() => dispatch(increment())}>+</button><button onClick={() => dispatch(decrement())} style={{ marginLeft: "10px" }}>-</button></div>);}export default App;