tezvyn:

Redux: A Single Source of Truth for App State

AI-drafted, machine-checkedSource: redux.js.orgintermediate

Redux centralizes app state into a single "store." Instead of components managing state locally, they dispatch actions to a global reducer. Use it when many components share data.

WHY IT EXISTS: As applications grow, managing state that's shared across many components becomes chaotic. Passing data through many layers of components or having multiple, out-of-sync copies of the same state leads to bugs. Redux was created to provide a predictable, centralized pattern for managing this global state.

THE MENTAL MODEL: Think of your application's entire state as one large JavaScript object living in a single container called the "store." This store is the single source of truth. You cannot modify the state directly. To make a change, you must dispatch an "action"—a plain object describing what happened.

HOW IT WORKS: The Redux flow has three parts. First, an event in your UI dispatches an action object (e.g., { type: 'counter/incremented' }). Second, the store sends this action and the current state to a "reducer." A reducer is a pure function you write that takes the old state and the action, and returns the new state. Third, the store saves the new state object and notifies the UI to re-render. The official Redux Toolkit (RTK) is the standard way to use Redux today. Its createSlice function generates reducers and actions for a piece of state, and configureStore sets up the store with best practices. RTK uses the Immer library, which lets you write simple "mutating" code (like state.value += 1) that it safely turns into a correct, immutable update.

WHEN TO USE IT: Use Redux when multiple parts of your app, which may be far apart in the component tree, need to access and manipulate the same state. It shines in large-scale applications where state changes need to be predictable, consistent, and easy to trace, especially with its time-traveling debugger.

WHEN NOT TO USE IT: Redux is overkill for simple applications. If your app's state is mostly local to individual components or can be managed with React's built-in useState or useContext hooks, adding Redux introduces unnecessary complexity. Don't use it just because it's popular; use it to solve a specific problem of complex, shared state.

ONE CANONICAL EXAMPLE: With Redux Toolkit, you define a "slice" of state for a feature like a counter. This slice specifies its initial state ({ value: 0 }) and its reducers (incremented, decremented). To increase the count from a component, you'd call store.dispatch(incremented()). The reducer logic, even if written as state.value += 1, is safely handled by RTK to produce a brand new, immutable state object, triggering a UI update.

Read the original → redux.js.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.