When the useEffect runs in Lazy Loaded Component
In React, when you use React.lazy() to dynamically import a component and then render it within a Suspense boundary, the lifecycle and loading behavior of the lazy-loaded component involve specific timing. Here's how it works in relation to useEffect:
Lifecycle of Lazy-Loaded Component
-
Initial Render:
- When the lazy-loaded component is first rendered, React starts fetching the component's code asynchronously. During this time, the fallback UI specified in the
Suspensecomponent is displayed.
- When the lazy-loaded component is first rendered, React starts fetching the component's code asynchronously. During this time, the fallback UI specified in the
-
Code Loading:
- Once the component's code has been fetched and evaluated, React renders the component with the
Suspensefallback replaced by the actual component.
- Once the component's code has been fetched and evaluated, React renders the component with the
-
useEffectExecution:- After the component is rendered, the
useEffecthook inside the lazy-loaded component will run. The execution ofuseEffecthappens after the component has been mounted in the DOM, which means it occurs after the component's code has been fully loaded and rendered.
- After the component is rendered, the
Summary of Timing
- Before
useEffectRuns: The component’s code is fetched and loaded asynchronously when usingReact.lazy(). During this loading phase, the fallback UI is displayed. - After
useEffectRuns: Once the lazy-loaded component has been successfully fetched and rendered,useEffecthooks within that component are executed. This meansuseEffectwill run only after the component has been fully loaded and mounted in the DOM.
Example
Here’s a simple example to illustrate:
// LazyLoadedComponent.js
import React, { useEffect } from 'react';
const LazyLoadedComponent = () => {
useEffect(() => {
console.log('useEffect runs after component mounts');
}, []);
return <div>Lazy Loaded Component</div>;
};
export default LazyLoadedComponent;
// App.js
import React, { Suspense, lazy } from 'react';
const LazyLoadedComponent = lazy(() => import('./LazyLoadedComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyLoadedComponent />
</Suspense>
);
}
export default App;
Execution Order
- Initial Render: When
Apprenders, React starts loadingLazyLoadedComponentand shows "Loading..." as the fallback. - Loading: React asynchronously fetches and evaluates
LazyLoadedComponent. - Rendering: Once
LazyLoadedComponentis fully loaded, React replaces the fallback withLazyLoadedComponent. useEffectExecution: After the component is rendered and mounted, theuseEffectinsideLazyLoadedComponentruns.
Published on: Jul 21, 2024, 02:24 PM