Home  Reactjs   When the us ...

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

  1. 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.
  2. 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.
  3. useEffect Execution:

    • After the component is rendered, the useEffect hook inside the lazy-loaded component will run. The execution of useEffect 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.

Summary of Timing

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

  1. Initial Render: When App renders, React starts loading LazyLoadedComponent and shows "Loading..." as the fallback.
  2. Loading: React asynchronously fetches and evaluates LazyLoadedComponent.
  3. Rendering: Once LazyLoadedComponent is fully loaded, React replaces the fallback with LazyLoadedComponent.
  4. useEffect Execution: After the component is rendered and mounted, the useEffect inside LazyLoadedComponent runs.
Published on: Jul 21, 2024, 02:24 PM  
 

Comments

Add your comment