Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.