Answer the question
In order to leave comments, you need to log in
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>
);
};
Answer the question
In order to leave comments, you need to log in
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 name
does 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 questionAsk a Question
731 491 924 answers to any question