Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Development build crashes when using React.lazy()

I am using react Lazy and Suspense for a component to load, but if i try to build the app using npm run build i get a error saying Error: Uncaught Error: Minified React error #294;, and also if I comment the lazy loading the build gets successful. code:

import { Suspense, lazy } from 'react';
const Component= lazy(() => import('./../location'));

const Homepage=()=>{
  return (
    <>
      <Suspense fallback={<div>Loading...</div>}>                
        <Component/>
      </Suspense>
    </>
  )
}
export default Homepage;
like image 856
Sanket Naik Avatar asked Dec 10 '22 02:12

Sanket Naik


2 Answers

This error hit in the path basically when we use ssr (server side rendering) or ReactDOMServer,

As React.lazy and Suspense are not yet supported by ReactDOMServer, you need to use dynamic import and remove Suspense and React.lazy to avoid this error.

like image 121
Piyush Zalani Avatar answered Dec 26 '22 12:12

Piyush Zalani


To resolve this is necessary load the Suspense component on front. The next sample use an useEffect to put on the on the Suspense component only if exists the window variable. The window variable only is used in the browser.

export const GuardLazyComponentToSSR: FunctionComponent = () => {
    const [isFront, setIsFront] = useState(false);

    useEffect(() => {
        process.nextTick(() => {
            if (globalThis.window ?? false) {
                setIsFront(true);
            }
        });
    }, []);

    if (!isFront) return null;

    return <Suspense fallback={() => 'loading'}>
        <MyLazyComponent></MyLazyComponent>
    </Suspense>;
}
like image 40
JonDotsoy Avatar answered Dec 26 '22 11:12

JonDotsoy