Skip to content

Instantly share code, notes, and snippets.

@riquito
Created April 16, 2018 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riquito/f9c1173116fce412238e58ce90146fec to your computer and use it in GitHub Desktop.
Save riquito/f9c1173116fce412238e58ce90146fec to your computer and use it in GitHub Desktop.
Wrap a component with a shouldComponentUpdate call
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';
}
@riquito
Copy link
Author

riquito commented Apr 16, 2018

It's useful for e.g. simple cases with styled-components to avoid having the component render every time

const StyledTitle = withShouldComponentUpdate(
    styled.h2`
        font-size: 18px;
    `,
    (nextProps, nextState) => false,
);

// <StyledTitle>Foo bar</StyledTitle>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment