Skip to content

Instantly share code, notes, and snippets.

@paularmstrong
Last active October 13, 2020 15:53
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save paularmstrong/cc2ead7e2a0dec37d8b2096fc8d85759 to your computer and use it in GitHub Desktop.
Save paularmstrong/cc2ead7e2a0dec37d8b2096fc8d85759 to your computer and use it in GitHub Desktop.
import hoistStatics from 'hoist-non-react-statics';
import React from 'react';
/**
* Allows two animation frames to complete to allow other components to update
* and re-render before mounting and rendering an expensive `WrappedComponent`.
*/
export default function deferComponentRender(WrappedComponent) {
class DeferredRenderWrapper extends React.Component {
constructor(props, context) {
super(props, context);
this.state = { shouldRender: false };
}
componentDidMount() {
window.requestAnimationFrame(() => {
window.requestAnimationFrame(() => this.setState({ shouldRender: true }));
});
}
render() {
return this.state.shouldRender ? <WrappedComponent {...this.props} /> : null;
}
}
return hoistStatics(DeferredRenderWrapper, WrappedComponent);
}
@ConAntonakos
Copy link

Thanks for this! Deferred rendering is very important in many cases, but not always intuitive as to what needs to be done to achieve the best UX. Do you mind explaining the significance of using hoist-non-react-statics and this double requestAnimationFrame trick?

@mkarajohn
Copy link

@ConAntonakos Maybe my answer comes too late, but hoist-non-react-statics takes any static methods and properties that you may have put on your component, and they are not set by React itself, and copies them (hoists them) on the wrapper component returned by the HOC.

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