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
Suspense
component 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
Suspense
fallback replaced by the actual component.
- Once the component's code has been fetched and evaluated, React renders the component with the
-
useEffect
Execution:- After the component is rendered, the
useEffect
hook inside the lazy-loaded component will run. The execution ofuseEffect
happens 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
useEffect
Runs: The component’s code is fetched and loaded asynchronously when usingReact.lazy()
. During this loading phase, the fallback UI is displayed. - After
useEffect
Runs: Once the lazy-loaded component has been successfully fetched and rendered,useEffect
hooks within that component are executed. This meansuseEffect
will 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
App
renders, React starts loadingLazyLoadedComponent
and shows "Loading..." as the fallback. - Loading: React asynchronously fetches and evaluates
LazyLoadedComponent
. - Rendering: Once
LazyLoadedComponent
is fully loaded, React replaces the fallback withLazyLoadedComponent
. useEffect
Execution: After the component is rendered and mounted, theuseEffect
insideLazyLoadedComponent
runs.
Published on: Jul 21, 2024, 02:24 PM