Home >Web Front-end >JS Tutorial >Lazy loading and Memoization | ReactJS | Part 1

Lazy loading and Memoization | ReactJS | Part 1

Linda Hamilton
Linda HamiltonOriginal
2024-11-25 21:08:10447browse

Lazy loading and Memoization | ReactJS | Part 1

Comparison of lazy loading and memoization in the context of ReactJS, with definitions, use cases, and examples:


Lazy Loading

Definition

Lazy loading in React refers to the practice of loading components or resources only when they are needed, rather than at the initial page load. This reduces the initial load time and improves performance.

Key Points

Goal: Reduce initial bundle size and optimize performance.

When Used: For components or assets that aren’t immediately required (e.g., a modal or an image in a hidden tab).

React Feature: Achieved using React.lazy and Suspense.

Example: Lazy loading a component

import React, { Suspense } from 'react';

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

const App = () => {
return (


Welcome to My App


Loading...}>



);
};

export default App;

Behavior: HeavyComponent will only be loaded when it's rendered.


Memoization

Definition

Memoization in React is the process of caching the result of a function or component rendering to avoid recalculating or re-rendering it unnecessarily. It helps improve performance by preventing redundant operations.

Key Points

Goal: Avoid expensive recalculations or re-renders.

When Used: For computationally expensive functions or components that receive the same props repeatedly.

React Features: Achieved using useMemo, useCallback, and React.memo.

Example: Memoizing a component

import React, { useMemo } from 'react';

const ExpensiveCalculation = ({ number }) => {
const calculate = (num) => {
console.log('Calculating...');
return num * 2; // Simulating an expensive operation
};

const result = useMemo(() => calculate(number), [number]);

return

Result: {result};
};

export default ExpensiveCalculation;

Behavior: calculate is only executed when the number prop changes, avoiding redundant calculations.


When to Use Each?

Lazy Loading:
Use when your application has large components or resources that can be deferred until needed (e.g., dashboard graphs or image-heavy galleries).

Memoization:
Use when your app performs repeated calculations or re-renders components unnecessarily due to unchanged props or state.

The above is the detailed content of Lazy loading and Memoization | ReactJS | Part 1. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn