React: change the component tree without unmounting/remounting certain components?

I have a wrapper component that’s dynamically loaded. While it’s loading, it’s just a div. I dynamically loaded it because it uses large libraries that I don’t want to include with the initial load.

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>;
}

The issue is that while Wrapper is loading, the child component renders and mounts. Then, when Wrapper loads, the child component unmounts, rerenders, and remounts. Is there a way to reuse the existing child component?

1 thought on “React: change the component tree without unmounting/remounting certain components?”

Leave a Comment