Home > Blockchain >  Is it valid, to update the state by mapping to new Objects
Is it valid, to update the state by mapping to new Objects

Time:06-13

Let's take this Update State example:

const initialState = [
    {id: 1, country: 'Austria'},
    {id: 2, country: 'Belgium'},
    {id: 3, country: 'Canada'},
  ];

  const [data, setData] = useState(initialState);

  const updateState = () => {
    setData(prevState => {
      const newState = prevState.map(obj => {
        if (obj.id === 2) {
          return {...obj, country: 'Denmark'};
        }

        return obj;
      });

      return newState;
    });
  };

1. Is it also valid to update the state like this? (First example)

  const updateState = () => {
    const newState = data.map(obj => {
      if (obj.id === 2) {
        return {...obj, country: 'Denmark'};
      }
      return obj;
    });

    setData(newState);
  };

2. Is it also valid to update the state like this? (Second example)

  const updateState = () => {
    setData(prevState => {
      const newState = prevState.map(obj => {
        if (obj.id === 2) {
          let newObj = obj;
              newObj.country = 'Denmark'
          return newObj;
        }

        return obj;
      });

      return newState;
    });
  };

3. Do this specific versions also have performance impacts? Which one is the best?

CodePudding user response:

The first and the second example are perfectly valid. I would, however, suggest you to use the first one and I will explain why:

  • With the first example you are using a callback as an argument of the function. And this form means that you are actually getting the last data state value (this is important because the state updates happen asynchronously). Whenever you need to update the state based on the previous value even React suggests to use the callback form to avoid side effects.

More infos here: https://reactjs.org/docs/hooks-reference.html#functional-updates

The third example is not valid because you are mutating directly the state. Something that in react is not allowed.

More infos here: https://dev.to/il3ven/common-error-accidentally-mutating-state-in-react-4ndg

  • Related