There's an object in my state
const [objCounter, setObjCounter] = useState({
title: "counter",
date: new Date()
});
When you click on the button changeTitle
is called and title
gets a random value from getRandomNumber
function:
const getRandomNumber = () => {
console.log("getRandomNumber called");
return Math.round(Math.random() * 20);
};
So my question is, why this changeTitle
function calls getRandomNumber
only one time:
const changeTitle = () => {
setObjCounter({
...objCounter,
title: `new title ${getRandomNumber()}` // console.log calls only once
})
};
but this one makes it called twice:
const changeTitle = () => {
setObjCounter((prevState) => ({
...prevState,
title: `new title ${getRandomNumber()}` // console.log calls twice
}));
}
Does it mean, that state can be changed in both ways, but the first solution is better due to performance issues?
Full codesandbox reproduction.