Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Sylvenas opened this issue Mar 29, 2021 · 4 comments
Closed

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

Sylvenas opened this issue Mar 29, 2021 · 4 comments

Comments

@Sylvenas
Copy link

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 ?

@a-c-sreedhar-reddy
Copy link

In StrictMode React rerenders the app two times (in dev mode) to detect and warn if there are side-effects while rendering.
So as long as there are no sideeffects in render,setState etc it should be fine.
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

@Sylvenas
Copy link
Author

@a-c-sreedhar-reddy thank you, this is a problem not a bug, this issus can be closed.

@bvaughn bvaughn closed this as completed Mar 30, 2021
@gaearon
Copy link
Collaborator

gaearon commented Mar 30, 2022

We've changed the logging behavior to be more intuitive in React 18.
#21783 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants