Redux as a Protocol for UI Changes
The store is the most boring part of Redux – the value lies in the message protocol of named, serializable actions that makes UI changes traceable, testable and open to discussion.
Redux as a Protocol for UI Changes
In networking, a protocol is not software but an agreement: it defines which messages may flow between parties, how each message is structured and what it means. TCP doesn’t dictate to anyone which program runs at the endpoints – it only determines the shape of the packets and the rules of the exchange. Exactly this notion, applied to a user interface, describes Redux more accurately than the usual shorthand.
That shorthand goes: Redux is a global state container for React applications. That isn’t wrong, but it points at the most boring part. Every application has an object that holds application state – as window.appState if need be, and that alone gains you nothing. What’s interesting about Redux is the agreement on how this object may change: exclusively through named, serializable messages. Redux is less a container than a protocol for changes – between the parts of the UI and, which is easily overlooked, across time. When you dispatch an action today, you are also talking to the colleague who reads the action log of a bug report in three months.
Three building blocks, very unevenly weighted#
Redux consists of three parts: the store, which holds the state, the actions, which describe changes, and the reducers, which compute the new state from the old state and an action. The store itself is surprisingly unspectacular – a few dozen lines around an object, a dispatch function and a list of subscribers. If you read the source code of createStore, you’re done in one cup of coffee.
The value lies in what the other two building blocks enforce. An action is a simple object with a type and a payload:
// actions.js
export const ORDER_SUBMITTED = 'ORDER_SUBMITTED';
export const ORDER_ACCEPTED = 'ORDER_ACCEPTED';
export const ORDER_REJECTED = 'ORDER_REJECTED';
export const submitOrder = order => ({
type: ORDER_SUBMITTED,
payload: { orderId: order.id, items: order.items }
});
No function pointer, no class instance, no reference to a component. Just data that can be written down as JSON. That looks like a restriction – and it is meant to be exactly that. A message that can be serialized can also be recorded, sent, compared and still read years later. A method call can do none of that.
The reducer is the second half of the agreement: a pure function that never triggers anything itself but only answers what a message means for the state.
// ordersReducer.js
import { ORDER_SUBMITTED, ORDER_ACCEPTED } from './actions';
const initialState = { pending: [], accepted: [] };
export default function ordersReducer(state = initialState, action) {
switch (action.type) {
case ORDER_SUBMITTED:
return { ...state, pending: [...state.pending, action.payload.orderId] };
case ORDER_ACCEPTED:
return {
...state,
pending: state.pending.filter(id => id !== action.payload.orderId),
accepted: [...state.accepted, action.payload.orderId]
};
default:
return state;
}
}
Almost everything teams value about Redux follows from this separation – message here, meaning there. It is usually filed under “predictability”. A different sorting helps me more:
- Every change can be recorded and replayed, because it exists as a data object.
- Every change can be tested without a browser, because the reducer is a pure function.
- Every change has a name that you can talk about in code review and with the business side.
- Every change can be observed from outside without touching the UI.
These are not four features. This is the same property four times: there is a protocol.
Time travel is not magic#
The Redux DevTools demonstrate this most impressively. Every action appears there as a line in a log, and because the state results only from folding all previous actions over the reducers, you can jump back anywhere in the log – the UI follows. The first time you show it, it looks like a trick. In fact, it is the mundane consequence of the protocol idea: if you know all messages and apply a deterministic function to them, you can reconstruct every intermediate state. Network people have known this forever – a packet capture plus a state machine gives you the complete session.
In a project this summer, exactly this spared us a stubborn bug. A user reported a state nobody could reproduce: an order that was displayed as open and confirmed at the same time. Instead of collecting guesses, we had the exported action history sent to us and replayed it locally. The faulty order – ORDER_ACCEPTED arrived before ORDER_SUBMITTED because two requests had overtaken each other – was there in black and white in the log after five minutes. With scattered setState calls, the same diagnosis would have been an afternoon with a debugger and luck.
Testing also benefits from the message form, without any test infrastructure at all:
// ordersReducer.test.js
import ordersReducer from './ordersReducer';
import { submitOrder } from './actions';
it('moves a submitted order into pending', () => {
const state = ordersReducer(undefined, submitOrder({ id: '42', items: [] }));
expect(state.pending).toEqual(['42']);
});
No DOM, no mock of a store, no rendering. Input, output, done. Reducer tests are among the few frontend tests I have never seen be flaky.
Events instead of commands#
This is also exactly where the value gets lost fastest, though – not because of the library but because of how the messages are cut. In a code review this spring, I was looking at a reducer whose action list looked like this: SET_LOADING_TRUE, SET_LOADING_FALSE, SET_ORDERS, SET_ERROR, RESET_ERROR. Formally, everything was correct: named, serializable objects, pure reducers, the DevTools work. Still, the protocol was worthless, because the messages didn’t describe what had happened but which field value the sender would like. That’s not an event protocol; those are remote assignments – setState with a detour and more typing.
The difference becomes clear in a direct comparison:
// commands: the sender prescribes how state must change
dispatch({ type: 'SET_LOADING_TRUE' });
dispatch({ type: 'SET_ORDERS', payload: orders });
dispatch({ type: 'SET_LOADING_FALSE' });
// events: the sender reports what happened in the domain
dispatch({ type: 'ORDERS_REQUESTED' });
dispatch({ type: 'ORDERS_LOADED', payload: { orders } });
dispatch({ type: 'ORDERS_LOADING_FAILED', payload: { error } });
The event variant has three properties that the command variant lacks. First, it brings domain language into the code: ORDER_SUBMITTED is a sentence the product owner understands too; SET_LOADING_TRUE is understood only by the author of the component. In review we then talk about the question “May a rejected order be resubmitted?” instead of boolean choreography. Second, an event is in the past and therefore undisputed – it is reported, not ordered. The sender doesn’t need to know who is listening. Third, and precisely for that reason, the circle of receivers scales: if a second reducer later needs to count the number of open orders for a badge, it simply subscribes to ORDER_SUBMITTED as well. With SET_ORDERS, the sender would have to be rebuilt. A command knows its receiver, an event knows only its cause – in the protocol picture, that’s the difference between an RPC call and a broadcast.
Since then, I read action files like a message directory. If they contain a vocabulary of the domain in the past tense, the protocol holds. If they contain a list of setters, the team has built a second setState mechanism, only more cumbersome.
sequenceDiagram participant V as View participant M as Middleware participant R as Reducer participant S as Store V->>M: dispatch(ORDER_SUBMITTED) Note over M: Listening point:<br/>logging, analytics, DevTools M->>R: action (unchanged) R->>S: new state S-->>V: notify + render
Middleware: listening in on the protocol#
If you take actions seriously as messages, you get a second capability for free that stays invisible in the container view: you can tap into the message stream. That’s exactly what middleware is – a function that sits between dispatch and the reducer and sees every message before it acquires meaning.
// analyticsMiddleware.js
const analyticsMiddleware = store => next => action => {
if (action.type.startsWith('ORDER_')) {
trackEvent(action.type, action.payload);
}
return next(action);
};
The triple-nested signature takes some getting used to, but it’s simply applied currying – I took apart how such function chains come about a few weeks ago in JavaScript Patterns That Stayed: Modules, Higher-Order Functions, Currying. More important than the form is the consequence: analytics doesn’t need a single call in a component. In the ordering project, the product analytics hang entirely on this one file. When a new metric was requested – how often a rejection follows a submission – that was a change in the middleware, not in thirty components. The same goes for logging in the error case: writing the last fifty actions into a ring buffer and attaching them to the error report costs twenty lines.
In the end, the async question is a protocol question too. Whether redux-thunk for the simple cases or redux-saga and redux-observable when flows have to be orchestrated – all three are middleware, and all three eventually flow back into ordinary actions. The asynchronous part doesn’t change the language; it just speaks it with a delay. How push and pull data flows fundamentally differ is covered in RxJS: Push and Pull – Redux consistently lives on the push side.
The limit: not every change deserves a message#
As useful as the protocol is, it has a price per message: a constant, an action creator, a reducer branch, and if in doubt a test. Only what is worth it should pay this price. Whether a dropdown is currently open, which tab is active, what is in an input field before it is submitted – that is local UI state, and it belongs in the component, in a plain setState. Nobody wants to read thirty INPUT_CHANGED between two domain events in the action log; the protocol gets noisy, and time travel turns into a slide show.
Dan Abramov himself wrote this down clearly last year in “You Might Not Need Redux”, and the text is not a distancing but a price list: the benefits of Redux arise precisely from its constraints, so it only pays off where you actually cash in those benefits. My check questions before state moves into the store:
- Do several components that are far apart in the tree read this state?
- Does the change have a domain name that would explain something in a bug report?
- Does anyone care about the history of these changes – support, analytics, debugging?
Three times no means: component. React has always been able to handle local state itself, and the just-released React 16 hasn’t changed that – the new Fiber core renders differently, but setState stays setState. The two mechanisms don’t compete; they serve different questions.
flowchart TD
A[State comes into being] --> B{Do distant<br/>components read it?}
B -- no --> L[Local:<br/>setState in the component]
B -- yes --> C{Domain name?<br/>History relevant?}
C -- no --> L
C -- yes --> S[Store:<br/>action + reducer]In the repository introduction-react, in which I have been collecting React topics for talks and examples since the spring, the Redux part is deliberately small for exactly this reason: a manageable example app in which the message vocabulary stays limited to a handful of domain events. Not because more wouldn’t be possible – but because the difference between protocol and container is easier to see in a small, clean vocabulary than in a large, noisy one.
What I take away from this#
Over time, I noticed that the teams who are happy with Redux and the ones who curse it aren’t using different libraries at all – they are using different protocols. The former have a vocabulary of domain events that you can read out loud; their action log reads like a running report of the application. The latter have setters in capital letters and wonder why the promised benefit fails to appear: the DevTools show noise, the tests check assignments, and there is nothing to discuss in review, because SET_VALUE contains no domain statement anyone could disagree with.
That’s why I now consider the store an implementation detail and the protocol the real architectural decision. The three questions that make the difference have little to do with the library: Which events exist in this application? What are they called in the language of the domain? And who may trigger them? If you have answered these questions, Redux gives you traceability, testability and a shared language almost for free. If you skip them, you get a global state container with ceremony – and then you really wouldn’t have needed Redux.
Should Redux be replaced by something else at some point, the exercise still remains valuable. A protocol of named, serializable change messages is not an invention of this library – networking has lived on it for decades, and so have event-driven systems on the server. Redux merely carried this discipline to a place where it used to be rare: right into the UI.
Further reading#
- MikeBild/introduction-react – repository with React examples, including a Flux/Redux part and an example app
- Redux documentation: Motivation – why mutation plus asynchrony is the real problem
- Dan Abramov: You Might Not Need Redux – the price list for the constraints, from the author himself
- React v16.0 release announcement – the fresh Fiber core, which changes nothing about the data flow model
Revised and translated from German with the help of AI.