Redux Reducer Complexity Issue

Viewed 777

I am currently re-writing a large desktop app in javascript - specifically, using React / Redux. The number of different Actions reflects the number of different ways that state may need to change. Currently, there are over 350 actions in this application.

The state is complex, and there are interdependencies on many different parts of the state tree, so combining reducers is not possible as the isolated state trees from different root reducers wont work for this application.

Therefore I have one primary reducer, with a switch statement for the actions - consisting of over 350 cases. For each case, I have to cherry pick the bits of the overal state needed, and pass it down to a child reducer explicitly. Most often, this child reducer (itself processing a large numner of action types) hands off to a variety of grandchild reducers and so on. Currently my reducer tree is 5 deep in places.

To add even more complexity, nearly 30% of my actions are asynchronous, so I'm using redux-thunk to deal with these - which is difficult to get right in this scenario.

My question is - is there a better flux implementation to handle this level of complexity, or is there a way to use Redux that is different from the norm, and allows me to manage this action/reducer complexity more easily?

Thanks

2 Answers

Instead of having one large reducer to share state, I would suggest providing more information in the action payloads and combining smaller reducers with combineReducers. You can do this using redux-thunk and the getState function parameter.

  function action(id) {
    return (dispatch, getState) => {
      const value = getState().ui.form.value; // read part of state tree
      dispatch({ type: 'ACTION', payload: { id, value } });
    }
  }

This way your reducers get all of the information they need in the action payload rather than having to share portions of state.

While dividing up reducers by slices of state is the recommended approach, you can split up the internal logic of your root reducer function any way you want. That includes running multiple "top-level" reducer functions in sequence.

I'd encourage you to read the the Redux docs section on "Structuring Reducers", which gives examples of different ways to split up your reducer logic. In particular, see the topics on Normalizing State Shape, Beyond combineReducers, and Reusing Reducer Logic.

My "Practical Redux" tutorial series also demonstrates other ways to organize feature-specific reducer logic. In particular, see Practical Redux, Part 7: Form Change Handling, Data Editing, and Feature Reducers.

Related