reactjsreduxreducersredux-actions

one action updates multiple reducers performance issue


In the current app I have set up multiple redux reducers to store data. Lets just call them 'user-reducers' and 'pet-reducers'. The 2 are very similar, they both have a posts[]. Now whenever user likes a post inside posts[], an action 'likeDone' is fired. Now I have 2 choices of implementing the redux update:

Option 1: both 'user-reducers' and 'pet-reducers' listens to 'likeDone'. IMO, this is inefficient in the later stages when I have more similar reducers and all of them listing to one action.

Option 2: change 'likeDone' into 2 more explicit actions ex. 'likeUserPostDone' 'likePetPostDone' and each reducer reacts to the matched action. This way, reducer updates seem more efficient but there will be more action types later on which will end up with lots of 'switch - case' and I'm not sure if that is a good practice.

Thanks for reading and please tell me what's the best for my case.


Solution

  • Have both reducers listen to your action if they both change when that action occurs. All redux reducers efficiently listen to all dispatched actions. They ignore actions if it doesn't change state.

    const petPostReducer = (prev = defaultValue, action = {}) => {
      const { type, payload} = action;
      switch (type) {
        case "LIKE_DONE": {
          const {id} = payload || {};
          const oldItem = prev[id] || {}
          const newItem = {...oldItem, like: true}
          return {
            ...prev
            [id]: {...updateItem, [id]: newItem};
        }
        default: {
          return prev; // Ignore all other actions != LIKE_DONE
        }
      }
    };
    

    It is fine to create more explicit actions, but you usually want to do so when you have different actions. (There are always exceptions)

    When possible, avoid logic in your reducers.

    If pets and user data are very similar, consider changing your state shape and use one reducer posts.

    console.log(state.posts) =>
    {
       0: {type: 'user' like: false},
       1: {type: 'pet' like: false},
       2: {type: 'user' like: true},
    }
    

    Please avoid premature optimization. I often do things that are less efficient in favor of simple, concise, immutable, readable and useful code. If you are targeting a feature phone or find a real performance bottleneck, you will need to measure with performance monitoring tools. The JavaScript engine optimizations are continuously improving and results are often surprising.