Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent destroy/render the remote component every time re-rendering from the host #3478

Open
5 tasks done
ducdv-lumin opened this issue Feb 4, 2025 · 5 comments
Open
5 tasks done

Comments

@ducdv-lumin
Copy link

ducdv-lumin commented Feb 4, 2025

Describe the bug

When creating the remote component in the host using the createRemoteComponent function, every time I make a state change, the remote component flashes because it unmounts and mounts again. Here is a minimal example from the host, and I have ensured that the remote component from the remote repository works correctly without any issues.

import React, { useState } from 'react';
import { loadRemote } from '@module-federation/enhanced/runtime';
import { createRemoteComponent } from '@module-federation/bridge-react';

const Button = createRemoteComponent<any, any>({
  loader: () => loadRemote('remoteRepos/Button'),
  fallback: null,
  loading: null,
});

const CountContainer = () => {
   const [count, setCount] = useState(0);
   return <Button onClick={() => setCount(prevState => prevState + 1)}>Hit me! {count}</ Button>
}

export default CountContainer;

Used Package Manager

npm

System Info

System:
    OS: Linux 6.1 Manjaro Linux
    CPU: (8) x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
    Memory: 9.68 GB / 15.51 GB
    Container: Yes
    Shell: 5.9 - /bin/zsh
Binaries:
    Node: 18.20.5 - ~/.nvm/versions/node/v18.20.5/bin/node
    Yarn: 1.22.22 - ~/.nvm/versions/node/v18.20.5/bin/yarn
    npm: 10.8.2 - ~/.nvm/versions/node/v18.20.5/bin/npm
    pnpm: 9.15.0 - ~/.nvm/versions/node/v18.20.5/bin/pnpm

Validations

@danpeen
Copy link
Contributor

danpeen commented Feb 23, 2025

Hi @ducdv-lumin,

Thank you for reporting this issue and providing a minimal reproduction example. I have reproduced this issue and this pr releated seems not working, it's still rendered and destroyed every time the state changed. And I will take a look on how to solve this problem.

Sorry for the late response because I've been kind of busy these days. I'll keep you updated on the progress. Thank you for your patience!

@ducdv-lumin
Copy link
Author

ducdv-lumin commented Feb 24, 2025

Hi @danpeen Thank you for taking a look at my issue. Regarding my fixing PR, I'm not sure why it doesn't work for you. But anyway, I tried creating a minimal version of the createRemoteComponent function to resolve my issue (just a temporary solution until the issue is officially fixed), and it works perfectly as expected!

type LazyModuleFederationProps = {
  loading: React.ReactNode;
  loader: () => Promise<DefaultComponent<unknown>>;
};

type ModuleHandlers = {
  render(props: { dom: HTMLDivElement }): void;
  destroy(props: { dom: HTMLDivElement }): void;
};

type ModuleProps = {
  default(): ModuleHandlers;
};

const createLazyModuleFederation = ({ loader }: Pick<LazyModuleFederationProps, 'loader'>) =>
  React.lazy(async () => {
    const module = (await loader()) as unknown as ModuleProps;

    return {
      default: forwardRef((props: Record<string, unknown>, ref: Ref<HTMLDivElement>) => {
        const rootRef =
          ref && 'current' in ref
            ? (ref as React.MutableRefObject<HTMLDivElement | null>)
            : useRef<HTMLDivElement | null>(null);
        const renderDom = useRef<HTMLDivElement>(null);
        const moduleRef = useRef<ModuleHandlers>(null);

        useEffect(() => {
          const renderTimeout = setTimeout(() => {
            const moduleReturn = module.default();
            moduleRef.current = moduleReturn;
            renderDom.current = rootRef.current;
            moduleReturn.render({ dom: rootRef.current, ...props });
          });

          return () => {
            clearTimeout(renderTimeout);
            setTimeout(() => {
              moduleRef.current?.destroy?.({
                dom: renderDom.current,
              });
            });
          };
        }, []);

        return <div ref={rootRef} />;
      }),
    };
  });

// All implemented codes as minimal version are referenced from these sources:
// - https://github.com/module-federation/core/blob/main/packages/bridge/bridge-react/src/create.tsx
// - https://github.com/module-federation/core/blob/main/packages/bridge/bridge-react/src/remote/index.tsx

export default function lazyModuleFederation<T>(info: LazyModuleFederationProps) {
  return forwardRef((props: PropsWithoutRef<T>, ref: Ref<HTMLDivElement>) => {
    const LazyComponent = useMemo(() => createLazyModuleFederation(info), []);

    return (
      <ErrorBoundary shouldRenderEmpty>
        <React.Suspense fallback={info.loading}>
          <LazyComponent {...props} ref={ref} />
        </React.Suspense>
      </ErrorBoundary>
    );
  });
}

@danpeen
Copy link
Contributor

danpeen commented Feb 24, 2025

Hello @ducdv-lumin Thank you for your fixing code. Yesterday I have fixed it and can you try this version @module-federation/[email protected] to see if it works on your case? I appreciate your help very much~

@ducdv-lumin
Copy link
Author

Hi @danpeen, thank you for the fix, that version works great for me!

@danpeen
Copy link
Contributor

danpeen commented Feb 24, 2025

@ducdv-lumin OK, Thank you for validation. Then I'll submit a PR to address this. Thank you again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants