0

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.

lloydbanks
  • 63
  • 7
  • Your codesandbox link doesn't have any errors, nor does it show off that `getRandomNumber` is getting called twice: please change your code to actually show the problem you're asking about. But on a code note: if the only thing you have in your `objCounter` is a title and a date, (1) that var is clearly not an object counter and you should give it a better name, and (2) there's not much point in unpacking it if you're unpacking it to 2 values of which you then immediately change one. Be explicit instead and just say `title: objCounter.title`. – Mike 'Pomax' Kamermans Sep 26 '20 at 17:28
  • Strict mode is weird like that. If you don't want some functions to occasionally be called more times than you'd usually expect, you can disable it, if it's actually a problem – CertainPerformance Sep 26 '20 at 17:32
  • hi @Mike'Pomax'Kamermans, I didn't write about any errors, my question was about why console.log occurs twice when I pass callback to update the state. Just open console in codesandbox to see what I mean. btw, due to 'duplicate' mark on my question I see the case is in React.StrictMode, which seems true. But my last question still stays actual, what is the right way to update state in my case, when a computed value is returned in an external function? – lloydbanks Sep 26 '20 at 19:13

0 Answers0