Skip to content

React.StrictMode setState function is getting called twice #12961

@delwyn

Description

@delwyn

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions