Skip to content

The number of console.log calls in setState is incorrect #21126

Closed
@Sylvenas

Description

Hello, I'm confused about how useState and setState work, for a simple example:

import React, { useState } from 'react';

const globalLog = console.log.bind(window);

function App() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount((c) => {
      console.log('local log');
      globalLog('global log');
      return c + 1;
    });
  }
  return (
    <div className="App">
      <p>{count}</p>
      <button onClick={handleClick}>add</button>
    </div>
  );
}

You can use this prepared code example:https://codesandbox.io/s/goofy-sea-6evwt?file=/src/App.js

React StrictMode:

  • On the first click,local log and global log print once each.
  • On the second click, local log prints once, but global log prints twice.
  • Third,fourth..., same as the second time

General mode:

  • On the first click,local log and global log print once each.
  • Second,third,fourth..., same as the second time.

And I know React uses a cycle linked-list to store the updater,and call all updaters in a loop during the update phase the source code

So in strict mode, what does React do to the 'local' console.log and why does it only print once.

Is this a bug or a question ?

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions