Skip to content

Commit

Permalink
Merge pull request #15 from helpscout/static-style-update-perf
Browse files Browse the repository at this point in the history
Perf boost for static CSS rules 🚀
  • Loading branch information
ItsJonQ committed May 9, 2018
2 parents 962add3 + 7f8c1e0 commit 5451456
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
14 changes: 14 additions & 0 deletions src/withStyles/__tests__/withStyles.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,20 @@ describe('HOC Composition', () => {
expect(styles.position).toBe('absolute')
expect(el.prop('type')).toBe('submit')
})

test('Styles are preserved on re-renders', () => {
const wrapper = mount(<StyledButton />)
const el = wrapper.find('button').node

wrapper.setProps({ title: 'yup' })
wrapper.update()

const styles = window.getComputedStyle(el)

expect(styles.appearance).toBe('none')
expect(styles.background).toBe('red')
expect(styles.position).toBe('absolute')
})
})

describe('Multiple Composed Components', () => {
Expand Down
21 changes: 20 additions & 1 deletion src/withStyles/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ const withStyles = (styles = '', options = { scope: '' }) => Composed => {
}

componentDidMount () {
this.addRule()
}

componentDidUpdate (prevProps) {
this.maybeUpdateRule(prevProps)
}

/**
* Adds the CSS Rule to the <style> tag node.
*/
addRule () {
if (!id || !CSSRules || this.styleSheet.hasRule(id)) return

const cssStyles = this.makeStyles().rule
Expand All @@ -43,7 +54,15 @@ const withStyles = (styles = '', options = { scope: '' }) => Composed => {
this.styleSheet.addRule(id, cssStyles)
}

componentDidUpdate (prevProps) {
/**
* Updates CSS Rule based on prop changes, if applicable.
*/
maybeUpdateRule (prevProps) {
/**
* No need to update if the rule is static. This guard is to help
* with performance.
*/
if (typeof CSSRules === 'string') return
/**
* Tested in Enzyme, but difficult to set up Istanbul to report.
*/
Expand Down

0 comments on commit 5451456

Please sign in to comment.