Reputation: 78
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;
Upvotes: 4
Views: 9840
Reputation: 728
If anyone else comes across this problem, there are several solutions.
If you are using next.js and trying to use React.Suspense, you may face this error. In Next.js, you can solve this problem simply by using the built-in next/dynamic.
Note by Next.js: In import('path/to/component'), the path must be explicitly written. It can't be a template string nor a variable.
So here is example of using it when you need variable import path.
If for some reason you need to use exactly React.Suspense, you can use a solution like JonDotsoy's answer above, or you can create a hook like:
import {
useEffect,
useRef,
useCallback,
} from 'react';
/**
* Describes value returned by "useIsMounted" hook
* @typedef { () => boolean } TUseIsMountedReturn
*/
type TUseIsMountedReturn = () => boolean;
/**
* Hook allows you to determine if the component is in the DOM or the component is already unmounted
* @function useIsMounted (hook)
* @return { TUseIsMountedReturn } - returns function that returns a boolean value
*/
export const useIsMounted = (): TUseIsMountedReturn => {
const ref = useRef(false);
useEffect(() => {
ref.current = true;
return () => {
ref.current = false;
};
}, []);
return useCallback(() => ref.current, [ ref ]);
};
And use it like this:
const Component = () => {
const isMounted = useIsMounted()
const LazyComponent = React.lazy(() => import('./path/to/component'))
if (isMounted()){
return <LazyComponent />;
}
return <div>Fallback</div>
}
Upvotes: 1
Reputation: 114
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>;
}
Upvotes: 5
Reputation: 3934
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.
Upvotes: 10