Skip to content

Commit

Permalink
fix: safely remove style
Browse files Browse the repository at this point in the history
BREAKING CHANGE: This change drops support for React 15 and 16
  • Loading branch information
huozhi committed Jul 22, 2021
1 parent 2741879 commit e31dbb6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 44 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@
"xo": "0.24.0"
},
"peerDependencies": {
"react": "15.x.x || 16.x.x || 17.x.x"
"react": "17.x.x || 18.x.x"
},
"keywords": [
"babel-plugin-macros",
Expand Down
63 changes: 20 additions & 43 deletions src/style.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,30 @@
import { Component } from 'react'
import { useLayoutEffect } from 'react'
import StyleSheetRegistry from './stylesheet-registry'

const styleSheetRegistry = new StyleSheetRegistry()

export default class JSXStyle extends Component {
constructor(props) {
super(props)
this.prevProps = {}
}

static dynamic(info) {
return info
.map(tagInfo => {
const baseId = tagInfo[0]
const props = tagInfo[1]
return styleSheetRegistry.computeId(baseId, props)
})
.join(' ')
}

// probably faster than PureComponent (shallowEqual)
shouldComponentUpdate(otherProps) {
return (
this.props.id !== otherProps.id ||
// We do this check because `dynamic` is an array of strings or undefined.
// These are the computed values for dynamic styles.
String(this.props.dynamic) !== String(otherProps.dynamic)
)
}

componentWillUnmount() {
styleSheetRegistry.remove(this.props)
export default function JSXStyle(props) {
if (typeof window === 'undefined') {
styleSheetRegistry.add(props)
return null
}

render() {
// This is a workaround to make the side effect async safe in the "render" phase.
// See https://github.com/zeit/styled-jsx/pull/484
if (this.shouldComponentUpdate(this.prevProps)) {
// Updates
if (this.prevProps.id) {
styleSheetRegistry.remove(this.prevProps)
}

styleSheetRegistry.add(this.props)
this.prevProps = this.props
useLayoutEffect(() => {
styleSheetRegistry.add(props)
return () => {
styleSheetRegistry.remove(props)
}
}, [props.id, props.children, String(props.dynamic)])
return null
}

return null
}
JSXStyle.dynamic = info => {
return info
.map(tagInfo => {
const baseId = tagInfo[0]
const props = tagInfo[1]
return styleSheetRegistry.computeId(baseId, props)
})
.join(' ')
}

export function flush() {
Expand Down

0 comments on commit e31dbb6

Please sign in to comment.