[go: up one dir, main page]

0% found this document useful (0 votes)
3 views13 pages

React Optimization Techniques

The document outlines various React optimization techniques including Lazy Loading, List Virtualization, Memoization, Throttling and Debouncing, and the use of the Transition Hook. Each technique is explained with its purpose, benefits, and real-life examples, along with code snippets demonstrating their implementation. These techniques aim to enhance performance, reduce load times, and improve user experience in React applications.

Uploaded by

ecb20060
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

React Optimization Techniques

The document outlines various React optimization techniques including Lazy Loading, List Virtualization, Memoization, Throttling and Debouncing, and the use of the Transition Hook. Each technique is explained with its purpose, benefits, and real-life examples, along with code snippets demonstrating their implementation. These techniques aim to enhance performance, reduce load times, and improve user experience in React applications.

Uploaded by

ecb20060
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

React

Optimization
Techniques

Abhik Nayak
01

Techniques:
1. Lazy Loading
2. List Virtualization
3. Memoization
4.Throttling and Debouncing
5. Use Transition Hook
02

Lazy Loading:
What is it? Load components or resources only when
needed, instead of all at once.

Why it's needed:


Improve initial load time
Reduce unnecessary downloads

Real-life example: Think of a long e-commerce page.


Instead of loading all product pages upfront, only load
pages when the user visits them.

Reduces app size at startup


Optimizes performance for large apps
Especially useful for routes or images
03

Code Example:
import React, { lazy, Suspense } from "react";
import { BrowserRouter, Link,
Route, Routes } from "react-router-dom";
const Admin = lazy(() => import("./Admin"));

const LazyLoadingExample = () => {


return ( // Admin.js
<BrowserRouter>
<h1>Home Page</h1> import React from "react";
<Link to={"/admin"}>Admin</Link> const Admin = () => {
<Routes> return (
<Route <div>
path="/admin" <h1>Admin Page</h1>
element={ <p>Lorem ipsum*5000000....
<Suspense> </p>
<Admin /> </div>
</Suspense> )
} }
/ >
</Routes> export default Admin;
</BrowserRouter>
);
};

export default LazyLoadingExample;


04

List Virtualization:
What is it?Optimize the rendering of large lists by
only displaying the items that are currently visible
on the screen.

Why it's needed:


Avoid slow performance on lists with thousands
of items
Only render visible items

Real-life example: Imagine a social media feed


showing thousands of posts. With list optimizations,
only visible posts are rendered, improving scroll
performance.

Prevents lag from large lists


Only renders visible items
Reduces memory and CPU usage
05

Code Example:
import React from "react"; // Main component
import { List } from "react-virtualized"; function ListOptimization() {
import "react-virtualized/styles.css"; return (
// Fast and efficient way
// Your list data <List
const list = Array(20000) width={300}
.fill() height={300}
.map((_, index) => ({ rowCount={list.length}
id: index, rowHeight={20}
name: `Item ${index}`, rowRenderer={rowRenderer}
})); />

// Function to render each row // Normal Way (take time to load)


function rowRenderer({ index, key, style }) { // <>
return ( // <ul>
<div key={key} style={style}> // {list.map((li) => (
{list[index].name} // <li>{li.name}</li>
</div> // ))}
); // </ul>
} // </>
);
}

export default ListOptimization;


06

Memoization:
What is it? Memoizes a computed value, recalculating
only when dependencies change.

Why it's needed:


Avoids unnecessary recalculations
Boosts performance in components with expensive
calculations

Real-life example: In a dashboard showing analytics,


useMemo can cache expensive calculations like data
summaries.

Avoids re-rendering large components


Reduces computation time
Useful for data-heavy components
07

Code Example:
import React, { useMemo } from "react";

const MemoizedExample = () => {


const [count, setCount] = React.useState(0);
const [otherState, setOtherState] = React.useState("");

const expensiveComputation = (num) => {


let i = 0;
while (i < 1000000000) i++;
return num * num;
};

const memoizedValue = useMemo(() => expensiveComputation(count), [count]); // With Memo


(Fast)
// const memoizedValue = expensiveComputation(count); // Without Memo (Time taking)

return (
<div>
<p>Count: {count}</p>
<p>Square: {memoizedValue}</p>
<button onClick={() => setCount(count + 1)}>Increase Count</button>
<input
type="text"
onChange={(e) => setOtherState(e.target.value)}
placeholder="Type something to check rerendering"
style={{ width: "100%" }}
/>
</div>
);
};

export default MemoizedExample;


08 &
Throttling Debouncing:
What is it? Limits the rate at which a function is invoked
(throttling) or ensures a function runs only after it hasn’t
been called for a specified time (debouncing).

Why it's needed:


Improves performance for frequent user actions
Avoids overloading the browser with events

Real-life example: Imagine resizing a window or typing in a


search bar. Throttling ensures the resize event doesn't fire
continuously. Debouncing waits for the user to stop typing
before making a search request.

Reduces the number of API calls


Prevents performance degradation
Ideal for scroll, resize, or input events
Code Example:
// Throttling.js
09
import React, { useState, useEffect } from "react";

const Throttling = () => {


const [scrollPosition, setScrollPosition] = useState(0);

const handleScroll = () => {


setScrollPosition(window.scrollY);
}; // Throttled to run once every 1 second

const throttle = (func, delay) => {


let lastCall = 0;
return function (...args) {
const now = new Date().getTime();
useEffect(() => {
if (now - lastCall < delay) {
window.addEventListener("scroll",
return;
throttle(handleScroll, 1000));
}
return () => {
l a s t Ca l l = no w ;
window.removeEventListener("scroll",
f u n c (. . . ar g s ) ;
throttle(handleScroll, 1000));
};
};
};
}, []);

return (
<div>
<h1>Scroll position: {scrollPosition}</h1>
<div style={{ height: "200vh" }}>
Scroll down to see throttling in action!
</div>
</div>
);
};

export default Throttling;


Code Example: 101
// Debouncing.js
import React, { useState, useCallback } from "react";
import { debounce } from "lodash";

const Debouncing = () => {


const [searchTerm, setSearchTerm] = useState("");
const [displayTerm, setDisplayTerm] = useState("");

const handleSearch = useCallback(


debounce((term) => {
setDisplayTerm(term);
}, 500), // Debounced to execute 500ms after the user stops typing
[]
);

const handleChange = (e) => {


const term = e.target.value;
setSearchTerm(term);
handleSearch(term);
};

return (
<div>
<input
type="text"
value={searchTerm}
onChange={handleChange}
placeholder="Type to search"
/>
<p>Search results for: {displayTerm}</p>
</div>
);
};

export default Debouncing;


useTransition() 11

What is it? Delays non-urgent updates to maintain smooth


UI transitions.

Why it's needed:


Prevents janky UI when multiple state updates occur
Useful in apps with heavy state changes

Real-life example: Imagine typing in a search box that filters


a list. With useTransition, the input remains responsive
while filtering happens in the background.

Keeps the UI responsive


Prioritizes important state updates
Ideal for input-heavy forms or searches
Code Example: 12
const UseTransition = () => {
const [search, setSearch] = useState("");
const [filteredUsers, setFilteredUsers] = useState(users);
const [isPending, startTransition] = useTransition();

const handleChange = (e) => {


setSearch(e.target.value);
startTransition(() =>
setFilteredUsers(users.filter((user) => user.includes(e.target.value)))
);
};
return (
<>
<label>Input: </label>
<input onChange={handleChange} />
{isPending && <p>Loading...</p>}
{!isPending && filteredUsers.map((e) => <p>{e}</p>)}
</>
);
};

export default UseTransition;

You might also like