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 8a93b81
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 22 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

0 comments on commit 8a93b81

Please sign in to comment.