I have a wrapper component that I want to load dynamically because it uses hooks with large file size, but I can't code-split hooks directly. While the component is loading, I show a plain div instead. Once it has loaded, I swap it in.
E.g. the component tree looks like:
<WrapperDeferred>
<Child />
</WrapperDeferred>
WrapperDeferred looks something like:
let Wrapper;
function WrapperDeferred({ children }) {
const forceUpdate = useForceUpdate();
useEffect(() => {
if (!Wrapper) {
import('./Wrapper').then(module => {
Wrapper = module.default;
forceUpdate();
});
}
}, []);
return Wrapper ? <Wrapper>{children}</Wrapper> : <div>{children}</div>;
}
Wrapper just renders a div, so the HTML structure remains the same. The only difference is that Wrapper uses a bunch of hooks.
The issue is that after Wrapper loads, the child component unmounts, rerenders, and remounts. Is there a way to swap <div> to <Wrapper> without rerendering the child component? The child component already has React.memo.