Skip to content

Wrong styles applied during SSR hydration #351

Description

@javiertury

Styled components is applying wrong styles during SSR hydration. The problem is that styles in production builds are swapped across components. For instance, the class sc-16rshtk is applied to a ToolbarContainer but contains the styles of a FooterLink. I'm using gatsby with gatsby-theme-material-ui and gatsby-plugin-styled-components.

This didn't happen for client side rendering, only for SSR. Since it only affected components styled with styled-components, I tried to collect more information by assigning a displayName to each component, but it did nothing, classnames remained the same.

Then I found #261 and saw this comment. It says that styled-components should not be re-exported to make displayName work.

import styled from '../lib/styled-components'; //  Does not work :(
import styled from 'styled-components'; //  Works

After applying that change, I made a new production build and then discovered that SSR hydration was now working correctly. I suspect that babel-plugin-styled-components does not work if the package is re-exported.

This issue was very hard to debug.

If you were re-exporting the module to add theme type definitions, please use module augmentation instead.

// src/types/styled-components.ts
import type { Theme } from '@material-ui/core';

declare module 'styled-components' {
  export interface DefaultTheme extends Theme {
  }
}

Metadata

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