0Pricing
React Native Academy · Leçon

Créer des tranches avec createSlice

Définissez une tranche avec createSlice, déclarez l’état initial et les fonctions de réduction, puis exportez les créateurs d’actions générés automatiquement ainsi que la fonction de réduction.

Créer des tranches avec createSlice est une leçon React Native Academy gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage React Native Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours React Native Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

What Is a Redux Slice?

A slice is a self-contained piece of Redux logic for one feature of your app. It bundles the initial state, the reducer functions, and the auto-generated action creators together in a single file. The name comes from the idea that each slice represents a portion (slice) of the global Redux state tree.

Importing and Calling createSlice

createSlice is imported from @reduxjs/toolkit and accepts a configuration object with three required fields: name (a string prefix for action types), initialState (the starting value for this slice's state), and reducers (an object of reducer functions). It returns an object containing the slice reducer and the action creators.

import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {},
});

export default counterSlice.reducer;

Defining Reducer Functions

Each function you add to the reducers object becomes a case reducer that handles a specific action. RTK uses the Immer library under the hood, so you can write code that appears to mutate state directly — Immer converts it to an immutable update automatically. You never need to spread or copy the state object manually.

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment(state) {
      state.value += 1; // Immer makes this safe
    },
    decrement(state) {
      state.value -= 1;
    },
    incrementByAmount(state, action) {
      state.value += action.payload;
    },
  },
});

Auto-Generated Action Creators

createSlice automatically generates an action creator for each reducer function you define. You export them from the slice and call them when dispatching. The action creator name matches the reducer key, and the generated action type string follows the pattern sliceName/reducerName, for example counter/increment.

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// Using in a component:
import { useAppDispatch } from '../../store/hooks';
import { increment } from './counterSlice';

const dispatch = useAppDispatch();
dispatch(increment());          // { type: 'counter/increment' }
dispatch(incrementByAmount(5)); // { type: 'counter/incrementByAmount', payload: 5 }

Exporting the Reducer

The createSlice call returns an object with a reducer property. You export this as the default export and then import it in your store configuration. RTK composes all your slice reducers into the single root reducer automatically when you pass them to configureStore.

// counterSlice.ts
const counterSlice = createSlice({ /* ... */ });
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;

// store/index.ts
import counterReducer from '../features/counter/counterSlice';
export const store = configureStore({
  reducer: { counter: counterReducer },
});

Defining TypeScript State Types

When using TypeScript, explicitly type your initialState so RTK can infer state and action types throughout the slice. Define an interface for your state and assign it as the type annotation on initialState. RTK will then infer the correct type for the state parameter in every reducer function automatically.

interface CounterState {
  value: number;
  status: 'idle' | 'loading' | 'failed';
}

const initialState: CounterState = {
  value: 0,
  status: 'idle',
};

const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment(state) {
      state.value += 1; // TypeScript knows state is CounterState
    },
  },
});

Using PayloadAction for Typed Payloads

When a reducer receives data from the dispatched action, import PayloadAction from RTK to type the action parameter. PayloadAction<number> tells TypeScript that action.payload must be a number. This prevents accidental mismatches between what the action creator accepts and what the reducer expects.

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    incrementByAmount(state, action: PayloadAction<number>) {
      state.value += action.payload;
    },
  },
});

The prepare Callback

The prepare callback lets you customize the action creator before RTK dispatches the action. You use it when you need to generate an ID, format data, or add a timestamp to the payload. The object returned by prepare must have a payload field, and optionally meta and error fields.

import { nanoid } from '@reduxjs/toolkit';

const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    addTodo: {
      reducer(state, action: PayloadAction<{ id: string; text: string }>) {
        state.push(action.payload);
      },
      prepare(text: string) {
        return { payload: { id: nanoid(), text } };
      },
    },
  },
});

Resetting and Replacing State

Sometimes you need to reset a slice to its initial state — for example on user logout. You can return a completely new state value from a reducer instead of mutating. If you return a value, Immer uses it as the next state. This is the correct pattern for resetting or fully replacing state in a slice reducer.

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0, status: 'idle' },
  reducers: {
    reset() {
      // Return the fresh initial value instead of mutating
      return { value: 0, status: 'idle' };
    },
  },
});

Responding to Actions from Other Slices

Slices can respond to actions defined in other slices using extraReducers. This avoids tight coupling — instead of importing one slice into another, you import only the action creator. Use the builder.addCase pattern to handle external action types inside your slice without adding them to the reducers key.

import { userSlice } from '../user/userSlice';

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [] },
  reducers: { /* own actions */ },
  extraReducers: (builder) => {
    builder.addCase(userSlice.actions.logout, (state) => {
      state.items = []; // clear cart when user logs out
    });
  },
});

Complete Counter Slice Example

Here is a complete, production-ready counter slice combining everything covered so far: a typed state interface, typed action creators with PayloadAction, and a reset action. Import this reducer into configureStore and its actions into components to have a fully working Redux feature.

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface CounterState { value: number; }
const initialState: CounterState = { value: 0 };

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => { state.value += 1; },
    decrement: (state) => { state.value -= 1; },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
    reset: () => initialState,
  },
});

export const { increment, decrement, incrementByAmount, reset } = counterSlice.actions;
export default counterSlice.reducer;

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: createSlice bundles initial state, reducers, and action creators together, Immer lets you write mutating-style reducer code that stays immutable, and PayloadAction types the action payload for TypeScript safety. Next up we explore reading state with useSelector.

Questions Fréquemment Posées

La leçon « Créer des tranches avec createSlice » est-elle gratuite ?

Oui — le texte complet de « Créer des tranches avec createSlice » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours React Native Academy, passe à CoddyKit PRO. Le cours React Native Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Créer des tranches avec createSlice » ?

Définissez une tranche avec createSlice, déclarez l’état initial et les fonctions de réduction, puis exportez les créateurs d’actions générés automatiquement ainsi que la fonction de réduction. Tu pratiques React Native Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer React Native Academy ?

Aucune expérience préalable n'est requise. React Native Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.

Combien de temps prend la leçon « Créer des tranches avec createSlice » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon React Native Academy ?

Oui. Chaque leçon React Native Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Configurer le magasin Redux et le Provider
  2. Créer des tranches avec createSlice
  3. Lire l’état avec useSelector
  4. Thunks asynchrones avec createAsyncThunk
← Retour à React Native Academy