Skip to content

Instantly share code, notes, and snippets.

@sachin-hg
Created January 11, 2023 07:27
Show Gist options
  • Save sachin-hg/2d1f168729d227f1ed080438dcc46e54 to your computer and use it in GitHub Desktop.
Save sachin-hg/2d1f168729d227f1ed080438dcc46e54 to your computer and use it in GitHub Desktop.
// read this: https://github.com/reactwg/react-18/discussions/110
import React, { useMemo, useInsertionEffect, forwardRef } from 'react'
const insertedRules =
typeof window !== 'undefined' && window.__SSR_STYLES__
? window.__SSR_STYLES__
: {}
function getStyleForRule (url, content) {
if (content) {
const style = document.createElement('style')
style.setAttribute('data-href', url)
style.appendChild(document.createTextNode(content))
return style
}
const link = document.createElement('link')
link.href = url
return link
}
function exists (url) {
if (insertedRules[url]) {
return true
}
return false
}
export function useStyles (styles) {
useInsertionEffect(() => {
s.forEach(({ url, content }) => {
if (!exists(url, content)) {
insertedRules[url] = true
document.head.appendChild(getStyleForRule(url, content))
}
})
}, [...styles])
}
function Styles ({ styles }) {
useStyles(styles)
return null
}
export default (Component, styles) => {
return forwardRef(function (props, ref) {
return (
<>
<Styles styles={styles} />
<Component {...props} ref={ref} />
</>
)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment