React Optimization Techniques
React Optimization Techniques
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.
Code Example:
import React, { lazy, Suspense } from "react";
import { BrowserRouter, Link,
Route, Routes } from "react-router-dom";
const Admin = lazy(() => import("./Admin"));
List Virtualization:
What is it?Optimize the rendering of large lists by
only displaying the items that are currently visible
on the screen.
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}
})); />
Memoization:
What is it? Memoizes a computed value, recalculating
only when dependencies change.
Code Example:
import React, { useMemo } from "react";
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>
);
};
return (
<div>
<h1>Scroll position: {scrollPosition}</h1>
<div style={{ height: "200vh" }}>
Scroll down to see throttling in action!
</div>
</div>
);
};
return (
<div>
<input
type="text"
value={searchTerm}
onChange={handleChange}
placeholder="Type to search"
/>
<p>Search results for: {displayTerm}</p>
</div>
);
};