question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[examples] cache.compat = true flickering when outside the Next.js's <Component />

See original GitHub issue
  • The issue is present in the latest release.
  • I have searched the issues of this repository and believe that this is not a duplicate.

Current Behavior 😯

https://github.com/mui-org/material-ui/blob/fd0664449604a390c6cebbcc5693bb3c934be52e/examples/nextjs/pages/_app.js#L11 https://github.com/mui-org/material-ui/blob/fd0664449604a390c6cebbcc5693bb3c934be52e/examples/nextjs/pages/_document.js#L10

this happens when the page starts loading

image

Expected Behavior 🤔

image

Steps to Reproduce 🕹

Live example

app.js

const cache = createCache({ key: "css", prepend: true });
cache.compat = true

export default function MyApp(props) {
  const { Component, pageProps } = props;
  return (
    <CacheProvider value={cache}>
      <Head>
        <title>My page</title>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
        <CssBaseline />
        <Paper sx={{ backgroundColor: "limegreen", width: "100%", height: 250 }}> {/* here */}
          <TextField placeholder="test placeholder" />
        </Paper>
        <Component {...pageProps} />
      </ThemeProvider>
    </CacheProvider>
  );
}

Steps:

  1. Clone example nextjs repository
  2. Place any Material-UI component outside the <Component /> in _app.js
  3. Keep clicking on the browser’s hit refresh button

Context 🔦

this happens in production mode

Your Environment 🌎

@material-ui/core”: “^5.0.0-alpha.38”, “@emotion/react”: “^11.4.0”, “@emotion/server”: “^11.4.0”, “@emotion/styled”: “^11.3.0”, “next”: “^11.0.1”,

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:4
  • Comments:12 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
ellcrevcommented, Jun 26, 2021

I get that same error in development too, but only when I use the Tabs component (because it uses :first-child). See this issue. If you aren’t using a Tabs component, then I’d report which component is throwing the console error. Either way, this bug is way smaller than the previous one as it only exists in development and this implementation does resolve the layout thrash.

2reactions
ellcrevcommented, Jun 26, 2021

I encountered this issue a couple days ago. I would recommend changing the _document’s getInitialProps to enhance the entire app rather than each page component. This allows CSSBaseline and other component styles that are outside <Component {...pageProps} /> to be rendered on the server as well.

_app.jsx (Remove the Cache Provider)

export default function MyApp(props) {
  const { Component, pageProps } = props;
  return (
    <>
      <Head>
        <title>My page</title>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
        <CssBaseline />
        <Paper sx={{ backgroundColor: "limegreen", width: "100%", height: 250 }}> {/* here */}
          <TextField placeholder="test placeholder" />
        </Paper>
        <Component {...pageProps} />
      </ThemeProvider>
    </>
  );
}

_document.jsx

MyDocument.getInitialProps = async (ctx) => {
  const originalRenderPage = ctx.renderPage;
  const cache = createCache({ key: "css", prepend: true });
  cache.compat = true;
  const { extractCriticalToChunks } = createEmotionServer(cache);

  // Wrap the entire app in the cache provider. This is used
  // instead of enhanceComponent.
  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) => (props) =>
        (
          <CacheProvider value={cache}>
            <App {...props} />
          </CacheProvider>
        ),
    });

  const initialProps = await Document.getInitialProps(ctx);
  const emotionStyles = extractCriticalToChunks(initialProps.html);
  const emotionStyleTags = emotionStyles.styles.map((style) => {
    return (
      <style
        data-emotion={`${style.key} ${style.ids.join(" ")}`}
        key={style.key}
        dangerouslySetInnerHTML={{ __html: style.css }}
      />
    );
  });
  return {
    ...initialProps,
    styles: [
      ...React.Children.toArray(initialProps.styles),
      ...emotionStyleTags,
    ],
  };
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

[examples] cache.compat = true flickering when outside the ...
The issue is present in the latest release. I have searched the issues of this repository and believe that this is not a...
Read more >
nextjs - page style not loading initially causing huge icons and ...
The simplest way I found to fix this is to add a loader which will look nice while the page loads and also...
Read more >
5 things not to do when building React applications
Learn five generally accepted development practices that developers can actually avoid when using React and alternative approaches.
Read more >
@mui/material | Yarn - Package Manager
React components that implement Google's Material Design. ... MUI Core contains foundational React UI component libraries for shipping new features faster.
Read more >
FAQs - styled-components
Total rewrite of the core stylesheet engine, tuned for performance. New hooks-based component model. StyleSheetManager has new props:.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found