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:

  <Child />

WrapperDeferred looks something like:

let Wrapper;

function WrapperDeferred({ children }) {
  const forceUpdate = useForceUpdate();

  useEffect(() => {
    if (!Wrapper) {
      import('./Wrapper').then(module => {
        Wrapper = module.default;
  }, []);

  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?

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

  1. 389300 771273Wow, great weblog layout! How lengthy have you ever been running a weblog for? you make running a blog glance effortless. The total appear of your internet site is magnificent, effectively the content material material! 935689


Leave a Comment