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.

CSS-in-JS Rendering Hooks

See original GitHub issue

šŸ’„ Proposal: Hooks for CSS-in-JS Client and Server Rendering

  • Guides / Styling and Layouts → Styling components with CSS-in-JS frameworks

So, the [v2] ā˜‚ļø Umbrella issue for v2 docs has the above open TODO (although the issue has been closed); and this is also currently mentioned in the docs as ā€œwelcoming PRsā€.

I have some experience with the setup patterns for emotion (incl. v11) and styled-components here, and would like to help with this. As far as I can tell from the source, this would require additions to the Lifecycle APIs so that the serverEntry.js and clientEntry.ts files’ rendering functions could be modified. I would need some guidance on creating these hooks.

Anyone want to help me get started?

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:7
  • Comments:24 (5 by maintainers)

github_iconTop GitHub Comments

8reactions
exahcommented, Jun 14, 2022

Hey guys,

I found a super hacky way to collect styles for styled-components, and I do not recommend it to anyone, but it works 😃. Most likely, it breaks hydration and forcing react to re-render the whole tree. Sadly, I don’t know how to force the non-production build to check, but honestly, this is much better than FOUC.

I’m voting for public API, which will allow returning your element before passing it to renderToString from react-dom/server.

Hacky way
  1. Create component for collecting styles from children:
import React from 'react'
import { renderToString } from 'react-dom/server'
import { ServerStyleSheet } from 'styled-components'
import { StaticRouter, useLocation } from 'react-router-dom'
import { HelmetProvider } from 'react-helmet-async'
import { Context as DocusaurusContext } from '@docusaurus/core/lib/client/docusaurusContext'
import useDocusaurusContext from '@docusaurus/useDocusaurusContext'

function ServerStyle({ from: children }) {
  let style = null

  const location = useLocation()
  const context = useDocusaurusContext()
  const sheet = new ServerStyleSheet()

  try {
    renderToString(
      sheet.collectStyles(
        <HelmetProvider>
          <StaticRouter location={location}>
            <DocusaurusContext.Provider value={context}>
              {children}
            </DocusaurusContext.Provider>
          </StaticRouter>
        </HelmetProvider>,
      ),
    )
    style = sheet.getStyleElement()
  } catch (error) {
    console.error(error)
  } finally {
    sheet.seal()
  }

  return style
}

function ClientStyle() {
  return null
}

export default typeof window === 'undefined' ? ServerStyle : ClientStyle
  1. And then render it in your Root:
// /src/theme/Root.js
import React from 'react'

import ServerStyle from './ServerStyle'

function Root({ children }) {
  return (
    <>
      <ServerStyle from={children} />
      {children}
    </>
  )
}

export default Root

UPD: Fixed DocusaurusContext imports UPD (2022-05-06): No longer works for v2.0.0-beta.16+ UPD (2022-06-10): Fixed for v2.0.0-beta.21+ thanks to @EmaSuriano!

4reactions
slorbercommented, Feb 17, 2021

@bennodev19 that’s something we want to work on but is not so simple. APIs are forever so we’d rather find a good abstraction for CSS-in-JS integration that will work for all the libs, not just SC. We could copy Gatsby’s abstraction but it’s also a good time to study what has worked well and not so well for Gatsby by studying all its CSS-in-JS plugins a bit.

You’d rather convert to css modules if you cannot wait because I don’t think we should rush on implementation without a careful design.

Read more comments on GitHub >

github_iconTop Results From Across the Web

JSS integration with React
React-JSS integrates JSS with React using the new Hooks API. ... Critical CSS extraction - only CSS from rendered components gets extracted.
Read more >
[react-jss] Investigate on how to support the new React hooks
We will create a prototype here: https://github.com/cssinjs/react-jss-hook and merge this into react-jss once the hook is stable enough andĀ ...
Read more >
cssinjs/Lobby - Gitter
If your functional components get too complex, you can move out hooks. Your business logic doesn't need to be defined in your render...
Read more >
Component-level CSS-in-JS - Ant Design
... component style will be regenerated during the rendering phase. ... @ant-design/cssinjs has a performance advantage whether it is theĀ ...
Read more >
Styling: CSS-in-JS - Next.js beta docs
A style registry to collect all CSS rules in a render. The new useServerInsertedHTML hook to inject rules before any content that might...
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