Reduce application events into immutable state
Quick answer
A reducer is a pure function from previous state and an action to next state. The application can replay an action sequence to inspect decisions and test behavior without rendering a UI.
How it works
Actions describe intent with a type and data. Validate actions at the boundary, then update only affected branches without mutating previous state. Return the same state for a defined no-op, so consumers may use identity to skip work. Replay assumes deterministic inputs; timestamps and random values must be explicit action data if needed. Avoid dispatching an effect from inside the reducer.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const reduce=(s,a)=>a.type==="ADD"?{...s,ids:[...s.ids,a.id]}:a.type==="CLEAR"?{...s,ids:[]}:s;const old={ids:["A"]};const next=reduce(old,{type:"ADD",id:"B"});console.log(JSON.stringify(old.ids),JSON.stringify(next.ids),reduce(next,{type:"OTHER"})===next);})()Expected console output:
["A"] ["A","B"] trueThe old array is unchanged, the new array has B, and the no-op preserves identity.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const reducer=(n,a)=>a.type==="INC"?n+a.by:a.type==="RESET"?0:n;const actions=[{type:"INC",by:3},{type:"RESET"},{type:"INC",by:2}];console.log(actions.reduce(reducer,0),actions.reduce(reducer,0));})()Expected console output:
2 2Both replays produce the same result from the same inputs.
Common mistakes
Do not mutate a nested array from the previous state after copying only the outer object. Return the original state for a documented no-op.
Practice
Replay ADD and CLEAR actions on a list reducer. Verify the original list is unchanged and unknown actions preserve identity.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reduce application events into immutable state — Knowledge Check
Apply the concept and reason about local example output.
What should a pure reducer depend on?
How should an unchanged branch usually be handled?
Why keep an ordered action sequence in a test?
What is the exact console output in Reduce application events into immutable state example 1?
(async () => {const reduce=(s,a)=>a.type==="ADD"?{...s,ids:[...s.ids,a.id]}:a.type==="CLEAR"?{...s,ids:[]}:s;const old={ids:["A"]};const next=reduce(old,{type:"ADD",id:"B"});console.log(JSON.stringify(old.ids),JSON.stringify(next.ids),reduce(next,{type:"OTHER"})===next);})()What is the exact console output in Reduce application events into immutable state example 2?
(async () => {const reducer=(n,a)=>a.type==="INC"?n+a.by:a.type==="RESET"?0:n;const actions=[{type:"INC",by:3},{type:"RESET"},{type:"INC",by:2}];console.log(actions.reduce(reducer,0),actions.reduce(reducer,0));})()