Created
April 16, 2018 15:30
-
-
Save riquito/f9c1173116fce412238e58ce90146fec to your computer and use it in GitHub Desktop.
Wrap a component with a shouldComponentUpdate call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, Fragment } from 'react'; | |
export const withShouldComponentUpdate = (WrappedComponent, func) => { | |
class WithShouldComponentUpdate extends Component { | |
displayName = `WithShouldComponentUpdate(${getDisplayName( | |
WrappedComponent, | |
)})`; | |
shouldComponentUpdate = (nextProps, nextState) => | |
func.call(this, nextProps, nextState); | |
render = () => ( | |
<Fragment> | |
<WrappedComponent {...this.props} /> | |
</Fragment> | |
); | |
} | |
WithShouldComponentUpdate.displayName = `WithShouldComponentUpdate(${getDisplayName( | |
WrappedComponent, | |
)})`; | |
return WithShouldComponentUpdate; | |
}; | |
function getDisplayName(WrappedComponent) { | |
return WrappedComponent.displayName || WrappedComponent.name || 'Component'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's useful for e.g. simple cases with styled-components to avoid having the component render every time