Skip to content

Instantly share code, notes, and snippets.

@sachin-hg
Created January 11, 2023 07:23
Show Gist options
  • Save sachin-hg/a391a3fddc202e8e41546cf32e111b16 to your computer and use it in GitHub Desktop.
Save sachin-hg/a391a3fddc202e8e41546cf32e111b16 to your computer and use it in GitHub Desktop.
import React, { createContext, forwardRef, useContext } from 'react'
import { useStream } from 'react-streaming'
export const StylesContext = createContext({ set: new Set() })
function assetToStyleString (asset) {
const { url, content } = asset
if (content) {
return `<style data-href="${url}">${content}</style>`
}
return `<link href="${url}">`
}
export const useStyles = (styles = []) => {
const { injectToStream } = useStream()
const context = useContext(StylesContext)
styles
.filter(({ url }) => {
return !context.set.has(url)
})
.forEach(asset => {
context.set.add(asset.url)
// this injectToStream needs to ensure that that our style tag is always sent before the HTML.
// so that we dont see a flash of unstyled content
injectToStream(
assetToStyleString(asset)
)
if (!context.noScripts) {
injectToStream(
`<script>window.__SSR_STYLES__['${asset.url}'] = true</script>`
)
}
})
}
export default (Component, styles = []) => {
return forwardRef(function (props, ref) {
useStyles(styles)
return <Component {...props} ref={ref} />
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment