| How to Investigate Slow React Page Loads :👈 | 👉:React with JavaScript and TypeScript |
Common React Optimization Mistakes |
Common React Optimization Mistakes
1. Introduction
React provides several techniques to improve application performance, including React.memo, useMemo, useCallback, lazy loading, code splitting, and virtualization.
However, using these techniques incorrectly can make an application more complex without improving performance. In some cases, unnecessary optimization can even make the application slower.
The goal is not to optimize every component. The goal is to identify actual performance bottlenecks and apply the right solution.
2. Using useMemo Everywhere
Mistake: Wrapping every calculation inside useMemo, even when the calculation is inexpensive.
Incorrect example:
function UserProfile({ name, age }) {
const fullName = useMemo(() => {
return name.toUpperCase();
}, [name]);
const userAge = useMemo(() => {
return age + 1;
}, [age]);
return (
<div>
<p>{fullName}</p>
<p>{userAge}</p>
</div>
);
}
These calculations are inexpensive. Memoization adds unnecessary complexity and dependency management.
Better approach:
function UserProfile({ name, age }) {
const fullName = name.toUpperCase();
const userAge = age + 1;
return (
<div>
<p>{fullName}</p>
<p>{userAge}</p>
</div>
);
}
When to use useMemo: Use it when a calculation is expensive and avoiding repeated calculations provides a measurable benefit.
3. Using useCallback for Every Function
Mistake: Wrapping every function in useCallback.
Incorrect example:
function UserProfile() {
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return <button onClick={handleClick}>Click</button>;
}
For a simple function that is not causing unnecessary child renders or affecting another optimization, useCallback may provide no meaningful benefit.
Better approach:
function UserProfile() {
function handleClick() {
console.log('Button clicked');
}
return <button onClick={handleClick}>Click</button>;
}
When to use useCallback:
- When passing a callback to a memoized child component and stable function identity helps avoid unnecessary renders.
- When a function is a dependency of another Hook and stabilizing it prevents unnecessary recalculation or effect execution.
- When profiling demonstrates a meaningful performance benefit.
4. Using React.memo on Every Component
Mistake: Wrapping every component with React.memo.
Example:
const Header = React.memo(function Header() {
return <h1>My Application</h1>;
});
If the component is inexpensive to render and does not receive frequently changing props, memoization may not be necessary.
Better approach:
Use React.memo for components that render expensive content or frequently receive unchanged props from a parent that renders often.
const ProductItem = React.memo(function ProductItem({ product }) {
return (
<div>
<h3>{product.name}</h3>
<p>{product.price}</p>
</div>
);
});
Important: React.memo performs a shallow comparison of props by default. It does not prevent renders caused by the component's own state changes or updates to context it consumes.
5. Ignoring State Placement
Mistake: Keeping all application state in the top-level App component.
When a high-level component updates frequently, many descendants may render again.
Example:
function App() {
const [search, setSearch] = useState('');
return (
<>
<Header />
<SearchBox value={search} onChange={setSearch} />
<Dashboard />
<Footer />
</>
);
}
If only the search interface needs this state, keeping it in the top-level component may cause unnecessary parts of the application to participate in updates.
Better approach: Move state closer to the components that use it.
function SearchSection() {
const [search, setSearch] = useState('');
return (
<>
<SearchBox value={search} onChange={setSearch} />
<SearchResults search={search} />
</>
);
}
function App() {
return (
<>
<Header />
<SearchSection />
<Dashboard />
<Footer />
</>
);
}
This limits the state update to the relevant part of the component tree.
6. Putting Everything into One Context
Mistake: Storing unrelated application data in a single React Context.
When the context value changes, components consuming that context can render again, even if they only use a portion of the value.
Better approach:
- Separate unrelated contexts, such as authentication, theme, and notifications.
- Keep frequently changing state close to where it is used.
- Consider context selectors or an appropriate state-management solution for complex applications.
- Profile before introducing additional state-management libraries.
7. Rendering Large Lists Without Virtualization
Mistake: Rendering thousands of records at the same time.
Example:
function UserList({ users }) {
return (
<div>
{users.map(user => (
<div key={user.id}>
{user.name}
</div>
))}
</div>
);
}
If the collection contains thousands of records, creating and maintaining all those DOM elements can affect rendering and scrolling performance.
Better approach:
- Use pagination when users need to browse data in pages.
- Use virtualization when users need to scroll through a large collection.
- Render only the visible items and a small buffer around them.
- Use stable and unique keys.
Libraries such as @tanstack/react-virtual can help implement virtualization.
8. Using Array Index as a Key
Mistake: Using the array index as the key for dynamic lists.
Example:
{users.map((user, index) => (
<UserItem key={index} user={user} />
))}
When items are inserted, removed, or reordered, indexes may refer to different records. This can cause incorrect component state reuse and unnecessary DOM updates.
Better approach:
{users.map(user => (
<UserItem key={user.id} user={user} />
))}
Use a stable, unique identifier associated with each record.
9. Loading the Entire Application at Once
Mistake: Importing every page and feature into the initial application bundle.
This increases the amount of JavaScript that users must download and execute before using the application.
Better approach: Use code splitting and lazy loading for features that are not immediately required.
import { lazy, Suspense } from 'react';
const Reports = lazy(() => import('./Reports'));
function App() {
return (
<Suspense fallback={<p>Loading reports...</p>}>
<Reports />
</Suspense>
);
}
For large applications, route-based code splitting is often a good starting point.
10. Making API Calls Unnecessarily
Mistake: Triggering API requests on every render or repeatedly fetching unchanged data.
Incorrect example:
function Users() {
const [users, setUsers] = useState([]);
fetch('/api/users')
.then(response => response.json())
.then(data => setUsers(data));
return <div>{users.length} users</div>;
}
The request runs during rendering. Updating state causes another render, which can trigger another request.
Better approach: Use an appropriate data-fetching mechanism. For a simple client-side example, an effect can be used:
import { useEffect, useState } from 'react';
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
const controller = new AbortController();
async function loadUsers() {
try {
const response = await fetch('/api/users', {
signal: controller.signal
});
if (!response.ok) {
throw new Error('Failed to load users');
}
const data = await response.json();
setUsers(data);
} catch (error) {
if (error.name !== 'AbortError') {
console.error(error);
}
}
}
loadUsers();
return () => controller.abort();
}, []);
return <div>{users.length} users</div>;
}
For larger applications, consider a data-fetching library or framework feature that supports caching, request deduplication, and loading states.
11. Using useEffect for Derived State
Mistake: Using an effect to calculate values that can be derived directly from existing state or props.
Unnecessary approach:
function ProductList({ products }) {
const [filteredProducts, setFilteredProducts] = useState([]);
useEffect(() => {
setFilteredProducts(
products.filter(product => product.price > 1000)
);
}, [products]);
return (
<div>
{filteredProducts.map(product => (
<p key={product.id}>{product.name}</p>
))}
</div>
);
}
This introduces an additional state update and render cycle.
Better approach:
function ProductList({ products }) {
const filteredProducts = products.filter(
product => product.price > 1000
);
return (
<div>
{filteredProducts.map(product => (
<p key={product.id}>{product.name}</p>
))}
</div>
);
}
If the calculation is expensive, consider useMemo. Do not create separate state for values that can be derived from existing data.
12. Ignoring Images and Static Resources
Mistake: Assuming React performance depends only on component rendering.
Large images, fonts, and other resources can make the page load slowly even when React rendering is efficient.
Better approach:
- Compress and resize images.
- Use WebP or AVIF where appropriate.
- Lazy-load below-the-fold images.
- Prioritize important above-the-fold images.
- Specify image dimensions.
- Optimize font loading.
- Use browser caching and a CDN where appropriate.
13. Performing Heavy Calculations on the Main Thread
Mistake: Performing CPU-intensive operations during rendering or inside event handlers.
Large calculations can block the browser's main thread, delaying rendering and user interactions.
Better approach:
- Optimize the algorithm first.
- Avoid repeating unnecessary calculations.
- Break large workloads into smaller tasks where appropriate.
- Use Web Workers for suitable CPU-intensive work.
- Use virtualization for large data displays.
Remember that useMemo avoids repeating some calculations; it does not move the calculation off the main thread.
14. Ignoring Production Performance
Mistake: Measuring application performance only in development mode.
React development builds include additional checks and development-related overhead. Therefore, their performance may not represent the production experience.
Better approach:
- Build the application using the production build command.
- Test the production output.
- Use realistic network and device conditions.
- Measure Core Web Vitals.
- Monitor real-user performance.
Also remember that React Strict Mode can intentionally run additional development checks. Do not treat every development-only render as a production performance problem.
15. Optimizing Without Measuring
Mistake: Applying optimization techniques based on assumptions rather than evidence.
For example, a developer may spend time optimizing component renders when the actual problem is a slow database query or a large API response.
Better approach:
- Reproduce the performance problem.
- Measure the current behavior.
- Use browser Network and Performance tools.
- Use React Profiler to inspect component rendering.
- Identify the actual bottleneck.
- Apply the appropriate optimization.
- Measure again and compare results.
16. React Optimization Mistakes: Quick Comparison
| Common Mistake | Better Practice |
|---|---|
| Using useMemo everywhere | Memoize expensive calculations when beneficial. |
| Using useCallback for every function | Stabilize callbacks when their identity matters. |
| Using React.memo everywhere | Memoize components with measurable rendering benefits. |
| Keeping all state in App | Move state closer to the components that use it. |
| Putting everything in one Context | Separate unrelated and frequently changing state. |
| Rendering thousands of list items | Use pagination or virtualization. |
| Using array indexes as keys | Use stable unique identifiers. |
| Loading all routes immediately | Use route-based code splitting. |
| Fetching data during rendering | Use effects or an appropriate data-fetching solution. |
| Using effects for derived state | Calculate derived values during rendering. |
| Ignoring static resources | Optimize images, fonts, and caching. |
| Optimizing without profiling | Measure, identify, optimize, and measure again. |
17. Interview Questions and Answers
Q1. Why should we not use useMemo everywhere?
Because memoization has its own overhead and adds dependency management. For inexpensive calculations, ordinary JavaScript may be simpler and sufficiently fast. useMemo should be used when avoiding repeated expensive calculations provides a measurable benefit.
Q2. What is the difference between React.memo and useMemo?
React.memo memoizes a component's rendered result based on its props. useMemo memoizes a calculated value inside a component between renders when dependencies remain unchanged.
Q3. Does useCallback prevent component re-rendering?
No. useCallback preserves a function reference between renders when dependencies remain unchanged. It can help prevent unnecessary child renders when used with React.memo, but it does not independently prevent rendering.
Q4. Why is using array indexes as keys discouraged?
Indexes can change when items are inserted, removed, or reordered. React may then associate component state with the wrong item. Stable unique identifiers help React track list items correctly.
Q5. How can React Context affect performance?
When a context value changes, components consuming that context can render again. Large contexts containing frequently changing unrelated values may cause unnecessary updates. Separating contexts and keeping state local can help.
Q6. What is list virtualization?
List virtualization renders only the visible items and a small surrounding buffer instead of rendering the entire collection. It reduces the number of DOM elements and can improve performance for large lists.
Q7. Does React.memo prevent all re-renders?
No. It can skip a parent-driven render when props are unchanged according to its comparison. The component can still render when its own state changes or when a context it consumes updates.
Q8. How do you decide whether optimization is necessary?
I reproduce the issue, measure performance, inspect browser and React profiling data, identify the bottleneck, and then apply a targeted optimization. I compare the results afterward to confirm the improvement.
18. Final Recommendations
- Keep components simple and focused.
- Keep state as close as practical to the components that need it.
- Use memoization only when it provides a measurable benefit.
- Use stable keys for dynamic lists.
- Use pagination or virtualization for large collections.
- Split large applications into smaller loading chunks.
- Avoid unnecessary API requests and repeated data processing.
- Optimize images and other static resources.
- Measure production performance and monitor real users.
Golden Rule: Good React optimization is not about using more performance Hooks. It is about writing efficient code, reducing unnecessary work, measuring actual bottlenecks, and applying the simplest solution that improves the user experience.
| How to Investigate Slow React Page Loads :👈 | 👉:React with JavaScript and TypeScript |
Comments and Discussion