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

React.StrictMode setState function is getting called twice #12961

Closed
delwyn opened this issue Jun 1, 2018 · 1 comment
Closed

React.StrictMode setState function is getting called twice #12961

delwyn opened this issue Jun 1, 2018 · 1 comment

Comments

@delwyn
Copy link

delwyn commented Jun 1, 2018

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
Calling setState with a function gets called twice on a components that is wrapped in React.StrictMode.

CodeSandbox (https://codesandbox.io/s/zl9rv0mmkx)

class Example extends React.Component {
  componentDidMount() {
    this.setState(() => {
      console.log(`Set state calls in ${this.props.name}`);
    });
  }

  render() {
    return <div>{this.props.name}</div>;
  }
}

const App = () => (
  <div>
    <React.StrictMode>
      <Example name="StrictMode" />
    </React.StrictMode>
    <Example name="Normal" />
  </div>
);

Will output

Set state calls in StrictMode 
Set state calls in StrictMode 
Set state calls in Normal 

What is the expected behavior?
setState function should only be called once in StrictMode

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
React: 16.4.0, 16.3.2
Browsers: Chrome, Firefox, Safari

@iamdustan
Copy link
Contributor

iamdustan commented Jun 1, 2018

This is intentional and why StrictMode exists. The double-invoking only happens in development mode.

https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

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

3 participants