Skip to content

Understanding one way data flows with Redux

Ray Millward edited this page Mar 15, 2019 · 3 revisions

In order to understand how the state and business logic links to the UI components we first need to revisit how data flows in a React-Redux system.

The main data contruct of a Redux system is the Store that contains a state, the state defines the UI and what is visible. A user then interacts with the UI and triggers actions which are sent to reducers, these reducers then update the state in the store.

In order to find out what updates to the store happen because of interactions with the UI it is important to follow this one-way data flow round the loop. From a component you will be able to find the actions that it fires (typically within the mapDispatchToProps method), you’ll then look for the reducer that handles the type in that action, from that reducer you can see the changes that are made to the state.

Each action should be of the form:

const actionType = 'A_CONSTANT_STRING_FOR_THE_ACTION';

const action = {
    type: actionType,
    payload: {
        someContents: {}
    }
};

const reducer = (state, action) => {
    switch (action.type) {
        case actionType:
            // do something with the actionType action
    }
};

It is important that the action does not contain a direct string for the type, instead it should be referenced from a constant. This then enables IDEs to search for all usages and it will immediately highlight the reducers that the action is handled in.

Another way of linking the UI components to the actions and reducers is by the naming convention, in general a login component will have a matching set of actions and a reducer; for example, the login component has actions in login.actions.js and a reducer in login.reducer.js.

Middleware

The one extra complexity behind the one-way data flow is the introduction of middleware. It's possible to add middleware to redux that intercepts an action and can do something with it before passing it on.

The most common use-case for this is if you have asynchronous actions (e.g. talking to an API server) - this is what the redux-thunk middleware is for.

Clone this wiki locally