JS Built-ins
redux-legacywithHistoryadvanced

Time-Travel with State History

πŸ“– Usage Example
const counterWithHistory = withHistory(counterReducer)

var s0 = counterWithHistory(undefined, { type: '@@INIT' })
// β†’ { present: 0, past: [] }

var s1 = counterWithHistory(s0, { type: 'INC' })
// β†’ { present: 1, past: [0] }

var s2 = counterWithHistory(s1, { type: 'UNDO' })
// β†’ { present: 0, past: [] }

withHistory wraps any reducer to add undo support, demonstrating the power of higher-order reducers in Redux.

Time-Travel with State History

A higher-order reducer can track the history of state to enable undo/redo. Wrap any reducer to store past states:

{
  present: currentState,
  past: [previousState1, previousState2, ...]
}

On a regular action: push current present onto past and compute the new present.
On UNDO: pop the last item from past and make it the new present.

Challenge: Implement withHistory(reducer) that wraps a reducer with full undo support.

πŸ’‘ Hints (2)
  • β€’ Store the wrapped reducer's initial state with `reducer(undefined, { type: '@@INIT' })` outside the returned function.
  • β€’ `state.past.concat([state.present])` creates a new array β€” never mutate `past` directly.