Home > Software engineering >  Why does the setter that takes a function returned by useState execute twice on a single call using
Why does the setter that takes a function returned by useState execute twice on a single call using

Time:01-26

Say you have the following state

const [elements, setElements] = React.useState([]);

The weird thing I noticed is when using the setter that takes a function, it seems to execute the console log twice and I don't know why. Any explanations?


const handleAddClick = (e) => {
    console.log("button clicked");
    setElements((elems) => {
      console.log("set elements called");
      return [...elems, "abc"];
    });
  };

Output

button clicked
set elements called
set elements called

CodePudding user response:

This is due to StrictMode.

In the list of StictMode actions it includes:

State updater functions (the first argument to setState)

In strict mode, state updater functions may be called twice to catch side effects. If your updater function is pure, it will not cause any issues - and the double update will not happen in production.

If your updater function mutates state, you will see odd behavior and it will help identify a bug.

  • Related