1

I've gotten rusty on Redux, and did not comment my code well. I looked in the console using console.log and I can't figure out what is going on.

I also looked at a cheat sheet here.

I've removed other cases to simplify the concerns.

const Articles = (state, action) => {
  
  console.log('state', state);
  let newState = { ...state };          // here?
  console.log('newState', newState);

  switch(action.type) {
    case "updateArticles":
      newState.articles = action.articles;
      break;
  }
  return newState;
};
clarissa
  • 163
  • 1
  • 2
  • 10

2 Answers2

1

This statement let newState = { ...state }; will clone the object into a new one. This is helpful to make sure you don't manipulate the old one by just doing let newState = state; and just passing the reference.

Dominik
  • 6,078
  • 8
  • 37
  • 61
1

In React (and redux), state should never be mutated, because React uses Object.is to determine whether a stateful value has changed (and if it doesn't detect a change, re-rendering will be skipped).

What you have there isn't destructuring, but spread syntax - you're creating a shallow copy of the state object and putting the copy into a variable named newState. This means that setting the new state to newState will result in re-rendering.

If you had mutated the old state instead by using the state variable instead of a new newState variable, you might well have not seen a re-render.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320