Home  Next-js   Lazy loadin ...

Lazy loading vs Partial rendering

Lazy loading and partial rendering are related concepts but are not exactly the same.

Lazy Loading

Lazy loading is a technique where certain parts of the application are loaded only when they are needed. This can help reduce the initial load time of the application and improve performance by splitting the code into smaller chunks and loading them on demand.

Partial Rendering

Partial rendering refers to the process of rendering only a portion of the page or component, instead of rendering the entire page or component from scratch. This can be particularly useful in applications where only a specific part of the UI needs to be updated frequently, without re-rendering the entire page.

Comparing Lazy Loading and Partial Rendering

Example of Partial Rendering in React

In React, partial rendering can be achieved using techniques like state management and React's built-in shouldComponentUpdate method (or equivalent hooks). For instance, using React's useState and useEffect hooks to update only a part of the component:

import React, { useState, useEffect } from 'react';

const PartialRenderingExample = () => {
  const [count, setCount] = useState(0);
  const [data, setData] = useState([]);

  useEffect(() => {
    // Fetch some data and update only when count changes
    fetch(`/api/data?count=${count}`)
      .then(response => response.json())
      .then(fetchedData => setData(fetchedData));
  }, [count]); // Only re-run the effect if count changes

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <p>Count: {count}</p>
      <div>
        {data.map(item => (
          <div key={item.id}>{item.name}</div>
        ))}
      </div>
    </div>
  );
};

export default PartialRenderingExample;

Example of Lazy Loading in React

Here's how you can implement lazy loading in React:

import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

const App = () => (
  <div>
    <h1>Welcome to the App</h1>
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  </div>
);

export default App;
Published on: Jul 16, 2024, 10:05 AM  
 

Comments

Add your comment