Actions and reducers for a PHP developer.

Redux is a predictable state container for Javascript apps. It manages state via actions and reducers.

Actions

The state cannot be updated with setters. This is done so that your code will not update the state arbitrarily, causing bugs. To change the state you have to dispatch an action. An action is a Javascript object that describes what happened. For example:

{
   type: 'ADD_TODO',
   text: 'Go to the swimming pool'
}

Enforcing that the state only changes via actions, gives us a clear understanding of what’s going on in the app.

Reducers

To tie state and actions together, you have to write a function, called a reducer. It’s just a function that takes the state and an action, it applies the changes from the action and returns the new state.

export default (state = [], action) => {
    if (action.type === 'ADD_TODO') {
        return state.concat({text: action.text, completed: false});
    }

    return state;
}

The action contains only the minimum information about the new change. The reducer is responsible for making that change correctly. The reducer should manage other logic like whether the item is completed. It would be a bad idea to add the completed flag to the action. Keep actions as simple as possible.

View components in your app are connected to the Redux state. When the state is updated, the component needs some logic to update itself.