DEV Community

Pranav Bakare
Pranav Bakare

Posted on

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs