Created
January 11, 2023 07:23
-
-
Save sachin-hg/a391a3fddc202e8e41546cf32e111b16 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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