D
D
Dmitry2020-09-26 19:52:13
JavaScript
Dmitry, 2020-09-26 19:52:13

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()
});

When the button is clicked, it is called and a random number from the function is added changeTitleto the property at the endtitlegetRandomNumber
const getRandomNumber = () => {
  console.log("getRandomNumber called");
  return Math.round(Math.random() * 20);
};

Question:
Why in this option, when clicking on the button, getRandomNumberit will work only 1 time
const changeTitle = () => {
  setObjCounter({
    ...objCounter,
    title: `new title ${getRandomNumber()}` // console.log вызывается один раз
  })
};

and in this (with the transfer of callback with the previous state) - twice?
const changeTitle = () => {
  setObjCounter((prevState) => ({
    ...prevState,
    title: `new title ${getRandomNumber()}` // console.log вызывается два раза
  }));
}

Which option is correct?

Full sandbox here

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-09-26
@dmitry-l

It turns out that these are the features of the work React.StrictMode. In develop mode, renders StrictModethe component twice to detect and warn about any problems with the code. create-react-appenables 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 question

Ask a Question

731 491 924 answers to any question