mangocaptain
mangocaptain

Reputation: 1495

State is contained in react redux actions vs. contained in reducers

I'm learning react-redux form the todo example in the docs and don't see why the id of the nextTodo is held in the actions rather than the reducer. Shouldn't this be considered state because it changes overtime as more todos are added? To me, the purpose of an action is to grab some input from the user and transform it to an action, not generate state. It is the reducer's job to create state and change it according to the actions given to it.

Action Code

let nextTodoId = 0

export const addTodo = (text) => {
  return {
    type: 'ADD_TODO',
    id: nextTodoId++,
    text
  }
}

Reducer code

const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false
      }
...
}

Upvotes: 0

Views: 103

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174957

That's because the reducer is expected to be a pure function. That is, if you run it multiple times with the same parameters, it would return the same result, and the state of the rest of the application would not change.

For that reason, the reducer can't determine the ID, as if it did, it would cause repeated runs to have different results (i.e. different return values).

The reducer's job isn't to create state. It's job is to get the existing state and a delta (i.e. an action) and return a new state. And it should do so reliably.

Upvotes: 3

Related Questions