hupe1980 / gatsby-plugin-material-ui

Gatsby plugin for Material-UI with built-in server-side rendering support
MIT License
136 stars 25 forks source link

[v4] gatsby-plugin-material-ui rearranges style order during hydration if <ThemeProvider> is used. #86

Open nagiek opened 2 years ago

nagiek commented 2 years ago

Problem In the root gatsby-ssr.js and gatsby-browser.js, I had wrapped my element with @mui's <ThemeProvider>. This worked OK for gatsby-ssr.js - styles came out where expected.

However, on the initial client re-render, the emotion <style> tags would be rearranged and moved to be the first child (from the last). I assume it is due to getting a different theme. I could not get this to work by putting the <ThemeProvider> into its own plugin.

You can see the official implementation here: https://mui.com/guides/server-rendering/#handling-the-request

This took a while to debug, hope it helps someone.

Old - within root gatsby-ssr.js:

export const wrapRootElement = (element) => {
  <ThemeProvider theme={theme}>
   {element}
  </ThemeProvider>
}

New - within new plugin (fork of this plugin):

export const wrapRootElement = (element) => {
  <CacheProvider cache={cache}>
    <ThemeProvider theme={theme}>
     {element}
    </ThemeProvider>
  </CacheProvider>
}

Using @emotion/styles 11.6 @emotion/react 11.6 gatsby 3.14.1 gatsby-plugin-material-ui v.4.1.0