Eric
Eric

Reputation: 61

Why does the setter that takes a function returned by useState execute twice on a single call using React?

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

Upvotes: 3

Views: 63

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14365

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.

Upvotes: 4

Related Questions