Answer the question
In order to leave comments, you need to log in
What is the correct way to use useState with an object?
I have an object stored in state
const [objCounter, setObjCounter] = useState({
title: "counter",
date: new Date()
});
changeTitle
to the property at the endtitle
getRandomNumber
const getRandomNumber = () => {
console.log("getRandomNumber called");
return Math.round(Math.random() * 20);
};
getRandomNumber
it will work only 1 timeconst changeTitle = () => {
setObjCounter({
...objCounter,
title: `new title ${getRandomNumber()}` // console.log вызывается один раз
})
};
const changeTitle = () => {
setObjCounter((prevState) => ({
...prevState,
title: `new title ${getRandomNumber()}` // console.log вызывается два раза
}));
}
Answer the question
In order to leave comments, you need to log in
It turns out that these are the features of the work React.StrictMode
. In develop mode, renders StrictMode
the component twice to detect and warn about any problems with the code. create-react-app
enables this mode by default. If you remove it or build the project, then re-rendering does not occur in the production assembly.
Concerning how to change object - it is possible and so and so.
If I'm wrong about something, I hope they will correct me or leave my answer.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question