Skip to content

Commit

Permalink
use getDerivedStateFromProps to count refs
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi committed Jul 9, 2021
1 parent 9ab4a77 commit 1ded933
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 25 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": "16.x.x || 17.x.x"
},
"keywords": [
"babel-plugin-macros",
Expand Down
34 changes: 13 additions & 21 deletions src/style.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const styleSheetRegistry = new StyleSheetRegistry()
export default class JSXStyle extends Component {
constructor(props) {
super(props)
this.prevProps = {}
this.state = {}
}

static dynamic(info) {
Expand All @@ -19,33 +19,25 @@ export default class JSXStyle extends Component {
.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)
)
static getDerivedStateFromProps(props, state) {
if (
props.id !== state.id ||
String(props.dynamic) !== String(state.dynamic)
) {
if (state.id) {
styleSheetRegistry.remove(state)
}
styleSheetRegistry.add(props)
return props
}
return null
}

componentWillUnmount() {
styleSheetRegistry.remove(this.props)
}

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
}

return null
}
}
Expand Down
13 changes: 10 additions & 3 deletions src/stylesheet-registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,10 @@ export default class StyleSheetRegistry {

remove(props) {
const { styleId } = this.getIdAndRules(props)
const hasId = styleId in this._instancesCounts
if (!hasId) return

invariant(
styleId in this._instancesCounts,
`styleId: \`${styleId}\` not found`
)
this._instancesCounts[styleId] -= 1

if (this._instancesCounts[styleId] < 1) {
Expand Down Expand Up @@ -210,3 +211,9 @@ export default class StyleSheetRegistry {
}, {})
}
}

function invariant(condition, message) {
if (!condition) {
throw new Error(`StyleSheetRegistry: ${message}.`)
}
}

0 comments on commit 1ded933

Please sign in to comment.