S
S
Shakir Darion2021-01-21 23:35:29
React
Shakir Darion, 2021-01-21 23:35:29

Why setMen(Men); change state?

this is my code

const App = () => {
  const [Men, setMen] = useState({ name: "dario" });
  console.log(Men)
  return (
    <div>
      <button
        onClick={() => {
          Men.name = "dario1"
          setMen(Men);
        }}
      >
        Add
      </button>
      <button
        onClick={() => {
          Men.name = "dario2"
          setMen({ ...Men });
        }}
      >
        Add1
      </button>
    </div>
  );
};


The state is updated when I click the Add button and then Add1. Why setMen(Men); change state?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Lewandowski, 2021-01-22
@vovaspace

There is something wrong with the wording of the question. When setMen(Men)there will be no re-render (the state will not change), because you pass the same object to the setter that is already in the state (since objects are compared by reference, and changing the field namedoes not change the reference).
When setMen({ ...Men })you pass a copy (a new object), so there will be a re-render. And Men.name = "dario2"there's nothing to do with it.
And the correct option in the end is this: About comparison by reference.
setMan({ ...Man, name: 'new name' });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question