Search code examples
javascriptreactjsreduxreact-reduxreducers

Destructing default state in redux reducer


What is the difference in returning state in default case in redux reducer between return state and return { ...state } ?


Solution

  • Like React, Redux uses immutability to efficiently check updated object references for updated state, which is why you should never modify/mutate state directly. In the default case of most reducers no actions have modified the state so you can return the original state object (return state), this is safe as it won't have been modified.

    However, return { ...state } will return an identical state but with a different top level object reference which will cause unnecessary checks for changed state. If you're not modifying state at all you should always return the original object (return state).

    EDIT: added on a follow up question - if you return { ...state } Redux would broadcast the updated state to all React components connected to the store (be it by hooks or the connect function) and then React would go into it's lifestyle cycle update. React is actually very efficient and uses memoizing and other methods to stop any expensive re-renders or repainting/regenerating the DOM so the difference between the 2 in terms of process will be next to nothing, it's just unnecessary. I don't think it'd even get to rerunning hooks suck as useEffect, it'd see the redundancy before getting there or at least use the memoize cache and not recalculate