Single Source of Truth: Centralized App State
A Single Source of Truth consolidates all application state into one central object, or 'store.' This makes state predictable and easier to debug, especially in libraries like Redux, by creating one place to look for data.
WHY IT EXISTS When an application grows, state can become scattered across many components. One component's state change might unexpectedly break another, leading to bugs that are difficult to trace. A Single Source of Truth (SSoT) was introduced to solve this chaos by providing one, and only one, place to find and manage an application's shared data.
THE MENTAL MODEL Think of your app's state as a single, large database record. Instead of individual components keeping their own private, conflicting notes, they all read from and request changes to this one central record. You can't scribble on the record directly; you must submit a formal change request form (an 'action'), ensuring all changes are orderly and tracked.
HOW IT WORKS In a library like Redux, the entire state of your application is stored in a single JavaScript object tree within a 'store'. To read data, a component gets it from the store. To change data, the component cannot write to the store directly. Instead, it dispatches an 'action'—a plain object describing 'what happened' (e.g., { type: 'ADD_TODO', text: 'Learn Redux' }). This action is processed by a 'reducer'—a pure function that takes the current state and the action, and returns a completely new state object reflecting the change. This read-only nature and use of pure functions ensures changes are predictable and centralized.
WHEN TO USE IT Use a global SSoT for state that is shared across many parts of your application. This includes things like user authentication status, data fetched from an API that multiple components need, or the contents of a shopping cart. It's essential for implementing complex features like undo/redo or time-travel debugging, which rely on having a complete, serializable history of the state.
WHEN NOT TO USE IT The primary footgun is putting everything in the global store. State that is truly local to one component, such as whether a dropdown is open or the current value of a form input, usually doesn't belong in a global store. Forcing it in adds unnecessary boilerplate and complexity, a problem known as 'prop drilling' in reverse.
ONE CANONICAL EXAMPLE In a Redux to-do list app, you wouldn't have a TodoList component managing the todos array and a Filter component managing the visibilityFilter string separately. Instead, the Redux store would hold a single state object like { todos: [...], visibilityFilter: 'SHOW_ALL' }. Both components would read their necessary data from this single source.
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.