Flux de données Redux

VérifiéSûr

Guide pour implémenter la boucle événement-réducteur-sélecteur-rendu de Redux, les actions de type événement, les transitions d'état gérées par les réducteurs et les données dérivées dans les applications Redux Toolkit.

Spar Skills Guide Bot
DeveloppementIntermédiaire
06/08/2026
Claude Code
#redux#state-management#redux-toolkit#selectors#dataflow

Recommandé pour

Synthèse automatique

Fournit les bonnes pratiques pour implémenter le cycle de données Redux avec Redux Toolkit : actions événementielles, transitions gérées par les reducers et sélecteurs de données dérivées.

Points forts

  • Propose un exemple minimal et complet (store, slice, sélecteurs, dispatch).
  • Met l'accent sur les actions événementielles et la propriété des transitions par les reducers.
  • Montre comment dériver des données avec des sélecteurs mémoïsés et des adaptateurs d'entités.
  • S'appuie sur les guides officiels de Redux et sa style guide.

Limites

  • Suppose une familiarité avec les concepts Redux/React et le typage TypeScript.
  • Ne couvre pas les flux asynchrones (thunks, createAsyncThunk) ni les middlewares.
  • Privilégie les schémas d'API plutôt que la configuration du débogage ou les devtools.
Quand l'utiliser

Lorsqu'on construit ou refactore une application Redux Toolkit et qu'on doit modéliser correctement les transitions d'état et les données dérivées.

Quand l'éviter

Avec une autre solution de gestion d'état (Zustand, MobX) ou lorsque les effets asynchrones sont le besoin principal.

Analyse de sécurité

Sûr
Score qualité90/100

The skill contains no executable commands, no network calls, no file system operations, and no dangerous constructs. It is purely a documentation pattern for Redux usage.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Set up Redux dataflow in a React app
I need to add Redux Toolkit to my React app and use the event -> reducer -> selector pattern. Show me how to define a slice with actions like postAdded and derive the visible list with a memoized selector.
Refactor a reducer with entity adapter
My Redux store has a posts array and I keep duplicating filtering logic in components. How should I model this with createEntityAdapter and createSelector?
Event-style vs generic setter actions
Should I dispatch a generic setState action or specific event actions like postPublished? What does the Redux style guide recommend?

name: build-modern-redux-apps/redux-dataflow description: > Use this when you need the Redux event -> reducer -> selector -> render loop, event-style actions, reducer-owned state transitions, derived data, or a debugging model for Redux Toolkit apps. type: core library: "@reduxjs/toolkit" library_version: "2.11.2" sources:

  • "reduxjs/redux:docs/tutorials/fundamentals/part-2-concepts-data-flow.md"
  • "reduxjs/redux:docs/tutorials/essentials/part-3-data-flow.md"
  • "reduxjs/redux:docs/style-guide/style-guide.md"

Redux Dataflow

Setup

import { configureStore, createSelector, createSlice } from '@reduxjs/toolkit'

const postsSlice = createSlice({
  name: 'posts',
  initialState: {
    items: [] as { id: string; title: string; published: boolean }[],
    filter: 'all' as 'all' | 'published',
  },
  reducers: {
    postAdded(state, action: { payload: { id: string; title: string } }) {
      state.items.push({ ...action.payload, published: false })
    },
    postPublished(state, action: { payload: { id: string } }) {
      const post = state.items.find((item) => item.id === action.payload.id)
      if (post) {
        post.published = true
      }
    },
    filterChanged(state, action: { payload: 'all' | 'published' }) {
      state.filter = action.payload
    },
  },
})

const store = configureStore({
  reducer: {
    posts: postsSlice.reducer,
  },
})

type RootState = ReturnType<typeof store.getState>

const selectPostsState = (state: RootState) => state.posts
const selectVisiblePosts = createSelector([selectPostsState], (postsState) =>
  postsState.filter === 'all'
    ? postsState.items
    : postsState.items.filter((post) => post.published),
)

store.dispatch(postsSlice.actions.postAdded({ id: 'p1', title: 'Draft' }))
store.dispatch(postsSlice.actions.postPublished({ id: 'p1' }))

const visiblePosts = selectVisiblePosts(store.getState())
console.log(visiblePosts)

Core Patterns

Dispatch events, not setters

const postsSlice = createSlice({
  name: 'posts',
  initialState: [] as { id: string; title: string }[],
  reducers: {
    postAdded(state, action: { payload: { id: string; title: string } }) {
      state.push(action.payload)
    },
    postRemoved(state, action: { payload: { id: string } }) {
      return state.filter((post) => post.id !== action.payload.id)
    },
    postUpdated(
      state,
      action: { payload: { id: string; changes: Partial<{ title: string }> } },
    ) {
      const post = state.find((item) => item.id === action.payload.id)
      if (post && action.payload.changes.title) {
        post.title = action.payload.changes.title
      }
    },
  },
})

postsSlice.actions.postAdded({ id: 'p1', title: 'Draft' })

Event-style actions explain what happened in the UI instead of hiding the transition behind a generic setter.

Let reducers combine old store data with new outside data

import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'

const postsAdapter = createEntityAdapter<{ id: string; title: string }>()

const postsSlice = createSlice({
  name: 'posts',
  initialState: postsAdapter.getInitialState(),
  reducers: {
    postsReceived(state, action: { payload: { id: string; title: string }[] }) {
      postsAdapter.upsertMany(state, action.payload)
    },
  },
})

const incomingPosts = [
  { id: 'p1', title: 'Draft' },
  { id: 'p2', title: 'Published' },
]

postsSlice.actions.postsReceived(incomingPosts)

If a transition mixes current store state with new external data, dispatch the new external data and let the reducer own the merge.

Derive values with selectors instead of storing duplicates

import { createSelector } from '@reduxjs/toolkit'

const selectPosts = (state: RootState) => state.posts.items
const selectFilter = (state: RootState) => state.posts.filter

export const selectVisiblePosts = createSelector(
  [selectPosts, selectFilter],
  (posts, filter) =>
    filter === 'all'
      ? posts
      : posts.filter((post) => post.published),
)

Selectors keep a single source of truth in state while still exposing the shapes the UI needs.

Common Mistakes

CRITICAL Mutating selected state outside reducers

Wrong:

const post = selectPostById(store.getState(), 'p1')

if (post) {
  post.title = 'Changed in place'
}

Correct:

store.dispatch(postUpdated({ id: 'p1', changes: { title: 'Changed in place' } }))

Objects read from the store are still store state; mutating them outside reducers breaks immutability and stale-render assumptions.

Source: reduxjs/redux:docs/style-guide/style-guide.md

HIGH Using setter-style actions instead of event-style actions

Wrong:

const nextPosts = [...selectPosts(store.getState()), { id: 'p2', title: 'Write docs' }]
store.dispatch(setPosts(nextPosts))

Correct:

store.dispatch(postAdded({ id: 'p2', title: 'Write docs' }))

Actions should describe events, not ask reducers to blindly replace state with a precomputed value.

Source: reduxjs/redux:docs/style-guide/style-guide.md

HIGH Combining store state before dispatch

Wrong:

const currentPosts = selectPosts(store.getState())
const mergedPosts = [
  ...currentPosts.filter(
    (currentPost) =>
      !incomingPosts.some((incomingPost) => incomingPost.id === currentPost.id),
  ),
  ...incomingPosts,
]

store.dispatch(postsReplaced(mergedPosts))

Correct:

store.dispatch(postsReceived(incomingPosts))

If the next state depends on current store state, the reducer should own that combination logic; only authoritative external snapshots should replace state wholesale.

Source: maintainer interview

HIGH Ignoring current state in async reducers

Wrong:

builder.addCase(fetchPosts.fulfilled, (state, action) => {
  state.status = 'succeeded'
  state.items = action.payload
})

Correct:

builder.addCase(fetchPosts.fulfilled, (state, action) => {
  if (state.status === 'pending') {
    state.status = 'succeeded'
    state.items = action.payload
  }
})

Reducers that treat every lifecycle action as valid can move the slice into impossible states or let stale requests win.

Source: reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md

MEDIUM Storing derived values in state

Wrong:

const initialState = {
  items: [] as Post[],
  visiblePosts: [] as Post[],
}

Correct:

const selectVisiblePosts = createSelector(
  [selectPosts, selectFilter],
  (posts, filter) =>
    filter === 'all' ? posts : posts.filter((post) => post.published),
)

Derived values drift out of sync quickly; keep the raw state and derive the view shape.

Source: reduxjs/redux:docs/style-guide/style-guide.md

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/redux-dataflow-msh3uugl/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/redux-dataflow-msh3uugl' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/redux-dataflow-msh3uugl/download' --output '.skill-downloads/redux-dataflow-msh3uugl/SKILL.md.part' && mv '.skill-downloads/redux-dataflow-msh3uugl/SKILL.md.part' '.skill-downloads/redux-dataflow-msh3uugl/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Extrait original : Setup
import { configureStore, createSelector, createSlice } from '@reduxjs/toolkit'

const postsSlice = createSlice({
  name: 'posts',
  initialState: {
    items: [] as { id: string; title: string; published: boolean }[],
    filter: 'all' as 'all' | 'published',
  },
  reducers: {
    postAdded(state, action: { payload: { id: string; title: string } }) {
      state.items.push({ ...action.payload, published: false })
    },
    postPublished(state, action: { payload: { id: string } }) {
      const post = state.items.find((item) => item.id === action.payload.id)
      if (post) {
        post.published = true
      }
    },
    filterChanged(state, action: { payload: 'all' | 'published' }) {
      state.filter = action.payload
    },
  },
})

const store = configureStore({
  reducer: {
    posts: postsSlice.reducer,
  },
})

type RootState = ReturnType<typeof store.getState>

const selectPostsState = (state: RootState) => state.posts
const selectVisiblePosts = createSelector([selectPostsState], (postsState) =>
  postsState.filter === 'all'
    ? postsState.items
    : postsState.items.filter((post) => post.published),
)

store.dispatch(postsSlice.actions.postAdded({ id: 'p1', title: 'Draft' }))
store.dispatch(postsSlice.actions.postPublished({ id: 'p1' }))

const visiblePosts = selectVisiblePosts(store.getState())
console.log(visiblePosts)

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Le fichier ne fournit pas un en-tête name/description exploitable pour cette procédure native. Le téléchargement reste disponible pour lecture ; utilisez le mode manuel ci-dessous.

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/redux-dataflow-msh3uugl/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires