0

Link to codesandbox-> https://codesandbox.io/s/musing-cori-hsjl0o?file=/src/App.js

I just want to clarify what is the better or correct way to update the state when modifying/updating a part of an existing state . Way 1 or Way 2 (highlighted the same above)

Please can someone share his/her views on this? Thanks.

import React from "react";
export default function App() {
  const [boxes, setBoxes] = React.useState([
    { number: 0, name: "BOX1" },
    { number: 0, name: "BOX2" },
    { number: 0, name: "BOX3" }
  ]);

  function incHandler(boxName) {
***    //Way 1
    // let new_boxes = boxes.map((e) => {
    //   if (e.name === boxName) {
    //     e.number++;
    //   }
    //   return e;
    // });
    // setBoxes([...new_boxes]);***

***    //Way 2
    setBoxes((prev) => {
      let new_boxes = prev.map((e) => {
        if (e.name === boxName) {
          e.number++;
        }
        return e;
      });
      return [...new_boxes];
    });***
  }
  return (
    <div className="App">
      {boxes.map((e) => {
        return (
          <div key={e.name}>
            {e.name}&nbsp;
            {e.number}&nbsp;
            <button
              onClick={() => {
                incHandler(e.name);
              }}
            >
              +
            </button>
          </div>
        );
      })}
    </div>
  );
}
  • 1
    Both are definitely incorrect, because they're mutating the existing state. Don't mutate state in React. – CertainPerformance Mar 08 '23 at 21:10
  • `map` already returns you a fresh array. You don't need to spread again just do: `setBoxes(boxes.map(e => e.name === boxName ? e.number++ : e));` – Doğukan Akkaya Mar 08 '23 at 21:14
  • @DoğukanAkkaya: It's best not to mutate state in React, even nested objects within that state. If `e.name === boxName` is true then a new object should be returned, not the same instance of `e` with a value modified. – David Mar 08 '23 at 21:16
  • Correct. Instead you can do `setBoxes(boxes.map(e => e.name === boxName ? {...e, number: e.number + 1} : e))` without mutating the state. – Doğukan Akkaya Mar 08 '23 at 21:29

0 Answers0