A user clicks a button, the application’s state changes, and the screen must catch up. A state manager keeps state and view in sync: it processes commands that update state, then tells the renderer to display the result. section 5.0
A small state manager has four connected responsibilities:
- Translate browser events into application commands. Clicking Add and pressing Enter can both dispatch `add-todo`; the command names what the application should do, not which browser event occurred. section 5.1.1
- Associate each command with a reducer. A reducer takes the current state and the command’s payload and returns the next state. section 5.1.2
- Use a dispatcher to call the appropriate reducer and store its returned state. section 5.1.2 section 5.2.3
- Notify the renderer after a command is handled. The renderer builds a view from the current state and mounts it in the DOM. section 5.2.2 section 5.2.3
Wire reducers to a renderer
Inside `createApp({ state, view, reducers })`, a compact version of the wiring is: const dispatcher = new Dispatcher() dispatcher.afterEveryCommand(renderApp) for (const actionName in reducers) { dispatcher.subscribe(actionName, (payload) => { state = reducers[actionName](state, payload) }) } For example, `removeTodo(state, todoIndex)` can return `state.toSpliced(todoIndex, 1)`. Once that command is handled, `renderApp()` uses `view(state)` to produce the new virtual DOM, destroys the previous DOM if present, and mounts the new view. This simple version re-renders after every command, even if the state did not change. section 5.1.2 section 5.2.3 section 5.2.2
Table 5.1 Mapping between browser events and application commands in the TODOs application
|
Browser event
|
Command
|
Explanation
|
|---|---|---|
|
Click the Add button.
|
add-todo
|
Clicking the Add button adds a new to-do item to the list.
|
|
Press the Enter key (while the input field is focused).
|
add-todo
|
Pressing the Enter key adds a new to-do item to the list.
|
|
Click the Done button.
|
remove-todo
|
Clicking the Done button marks the to-do item as done, removing it from the list.
|
|
Double-click a to-do item.
|
start-editing-todo
|
Double-clicking a to-do item sets the to-do item in edit mode.
|
The TODO command table makes the boundary between browser events and application actions concrete: different events can request the same state change. section 5.1.1
The first renderer replaces the whole DOM tree rather than updating only changed parts. That keeps the state-management wiring simple, but it is inefficient and can disrupt input focus; selective DOM updates are a later improvement. section 5.3 section 5.2.3








