Skip to content

Instantly share code, notes, and snippets.

@emeraldsanto
Last active April 13, 2023 21:34
Show Gist options
  • Save emeraldsanto/43ae63eff64cafbab58d6e4d740deabf to your computer and use it in GitHub Desktop.
Save emeraldsanto/43ae63eff64cafbab58d6e4d740deabf to your computer and use it in GitHub Desktop.
HOC to wrap a component in a `Suspense`, most likely a React Navigation screen. To be used with `React.lazy`.
/**
* Wraps the provide component in a `Suspense`, with the provided fallback.
* This should be used on components whose parent is not easy to control, such as
* React Navigation screens to be able to lazy load them using `React.lazy`.
* @param WrappedComponent The component to wrap.
* @param fallback The component to render while loading.
*
* @example
* const SomeScreen = withSuspense(React.lazy(() => import("path/to/some/screen")));
*/
export function withSuspense<P extends string | number | object>(WrappedComponent: ComponentType<P>, fallback: SuspenseProps["fallback"] = null) {
function ComponentWithSuspense(props: P) {
return (
<Suspense fallback={fallback}>
<WrappedComponent {...props} />
</Suspense>
);
}
return ComponentWithSuspense;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment