Importing Components

Remote Modules can be imported in various ways.

Lazy / Async import

Default Exports

Use React.lazy and React.Suspense

Hydration Errors

Using next/dynamic to import remote modules will cause Hydration Errors

import React, { lazy } from 'react';
const SampleComponent = lazy(() => import('next2/sampleComponent'));

const FormComponent = ()=>{
  return (
    <Suspense fallback="loading">
      <SampleComponent/>
    </Suspense>
  )
}

export default FormComponent

Named exports

Named Exports require a mocked default be returned to React.lazy which expects only default exports.

import React, { lazy } from 'react';

const SampleComponent = lazy(() => import('next2/sampleComponent').then((mod) => {
  return { default: mod.NamedComponent };
}));

const FormComponent = () => {
  return (
    <Suspense fallback="loading">
      <SampleComponent />
    </Suspense>
  );
};

export default FormComponent;

Eager / Sync import

Eager imports work as well, but it is reccomneded to use dynamic imports when possible to avoid large upfront network transfors or requests

let SomeHook = require('next2/someHook');
SomeHook = SomeHook.default || SomeHook;

import SomeComponent, {NamedExportComponent} from 'next2/sampleComponent';

Client side only

In some cases, you may just want to load a remote module on the client.

For example, if your remote does not provide a commonjs and browser build target.

Node requires a remoteEntry in commonjs format, you cannot provide a browser designated remote to a Server.

import {lazy, Suspense, useEffect, useState} from 'react';

const RemoteModule = typeof window === 'undefined' ? ()=>{} : lazy(() => import('app3/sampleComponent'));

const ClientOnly = ({Component}) => {
  const [mounted, setMount] = useState(false);
  useEffect(() => {
    setMount(true);
  }, []);
  if (!mounted) return null;
  return (
    <Suspense fallback="loading">
      <Component />
    </Suspense>
  );
};

const App = ()=>{
  return <ClientOnly Component={RemoteModule} />
}