JS Built-ins
redux-legacyreducerbeginner

Reducer with Default State

πŸ“– Usage Example
function reducer(state = 0, action) {
  if (action.type === 'INCREMENT') return state + 1
  return state
}
reducer(undefined, { type: '@@INIT' }) // β†’ 0  (default)
reducer(undefined, { type: 'INCREMENT' }) // β†’ 1

Providing a default parameter for state ensures the reducer initialises correctly when called by Redux.

Reducer with Default State

Redux calls your reducer with undefined the first time to initialise state. Use a default parameter to provide the initial value:

function reducer(state = 0, action) { ... }

When Redux dispatches its internal @@INIT action, your reducer returns the default state.

Challenge: Implement reducer(state = 0, action) that uses 0 as the default state and handles 'INCREMENT'.

πŸ’‘ Hints (2)
  • β€’ Default parameters: `function reducer(state = 0, action)` sets state to 0 when it is undefined.
  • β€’ Redux dispatches `{ type: "@@INIT" }` on startup to get the initial state.