Skip to content

Global styles does not work in React.StrictMode #3008

@perjansson

Description

@perjansson

Environment

System:
OS: macOS 10.15.1
CPU: (8) x64 Intel(R) Core(TM) i7-8569U CPU @ 2.80GHz
Memory: 857.00 MB / 16.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 10.15.3 - ~/.nvm/versions/node/v10.15.3/bin/node
Yarn: 1.16.0 - /usr/local/bin/yarn
npm: 6.4.1 - ~/.nvm/versions/node/v10.15.3/bin/npm
npmPackages:
styled-components: ^5.0.1 => 5.0.1
Reproduction
https://codesandbox.io/s/wonderful-hill-6glof

Steps to reproduce

Load the code sandbox
Click the button "to black" and then click again "to white" and notice how the background did not change back to black.

Expected Behavior

The should change between black and white

Actual Behavior

The background stays black after the first press on the toggle button. The global CSS (rendered by GlobalStyle in ComponentBlack) is added twice and only one is removed when unmounting when in Strict Mode. This is because to Strict Mode "intentionally double-invoking" some lifecycle methods to determine side effects that could be a problem in the upcoming async mode in React. When concurrent mode becomes available and React might call render function multiple times the side effect of setting global styles on render will cause issues like this.

As far as I can tell styled-components should be React.Strict compatible and using the createGlobalStyle util is the recommended way to do global styling with styled-components, so this seems to be a bug to me.

Metadata

Metadata

Assignees

No one assigned

    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