React Performance Best Practices
Learn how to improve React application performance by reducing unnecessary renders, optimizing calculations, loading components efficiently, and measuring performance with React Developer Tools.
1. Introduction to React Performance Best Practices
React performance optimization means improving the responsiveness and efficiency of an application without making the code unnecessarily complicated. A well-optimized application renders efficiently, loads resources appropriately, and provides a smooth experience for users.
React already has efficient rendering mechanisms. Developers should understand how components render, identify performance bottlenecks, and select the appropriate optimization technique.
For example, a student management application may display student records, courses, marks, reports, and dashboards. If every interaction causes expensive calculations or unnecessary component rendering, the application may become slow.
2. Understanding the Performance Optimization Process
Before optimizing a React application, developers should understand how the application behaves during rendering and user interactions.
React Performance Optimization Flow
How it works:
- Identify the component or operation causing a slowdown.
- Measure its rendering or calculation cost.
- Choose an optimization suitable for the problem.
- Check whether the change improves performance.
3. Keep Components Small and Reusable
Components should have clear responsibilities. Breaking a large interface into smaller components makes the application easier to understand, maintain, reuse, and optimize.
function StudentProfile() {
return (
<div>
<h3>Student Profile</h3>
<p>Name: Samadhan</p>
</div>
);
}
function StudentCourses() {
return (
<div>
<h3>Student Courses</h3>
<p>React Development</p>
</div>
);
}
function StudentResults() {
return (
<div>
<h3>Student Results</h3>
<p>Marks: 90</p>
</div>
);
}
export default function StudentDashboard() {
return (
<div>
<h2>Student Dashboard</h2>
<StudentProfile />
<StudentCourses />
<StudentResults />
</div>
);
}
Expected Output:
Student Dashboard
Name: Samadhan
React Development
Marks: 90
Explanation:
- StudentProfile displays student information.
- StudentCourses displays the enrolled course.
- StudentResults displays the student's result.
- StudentDashboard combines the smaller components.
4. Avoid Unnecessary Re-Renders with React.memo
When a parent component renders again, its child components may also render. If a child component is expensive and receives unchanged props, React.memo can help skip unnecessary renders.
import { memo } from 'react';
const StudentDetails = memo(function StudentDetails({ name }) {
console.log('StudentDetails rendered');
return (
<div>
<h3>Student: {name}</h3>
</div>
);
});
export default StudentDetails;
import { useState } from 'react';
import StudentDetails from './StudentDetails';
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Student Dashboard</h2>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase Counter
</button>
<StudentDetails name="Samadhan" />
</div>
);
}
Expected Output:
Student Dashboard
Counter: 0
When the counter changes, StudentDetails can skip rendering because its name prop remains unchanged.
Explanation:
- useState stores the counter value.
- Clicking the button updates the counter.
- The parent component renders again after the state update.
- React.memo compares the child component's props.
- If its props remain unchanged, React can skip the child render.
5. Use useMemo for Expensive Calculations
The useMemo Hook caches a calculated value between renders while its dependencies remain unchanged. It can help avoid repeating expensive calculations when unrelated state changes.
import { useMemo, useState } from 'react';
const initialMarks = [70, 85, 90];
export default function StudentMarks() {
const [marks] = useState(initialMarks);
const [count, setCount] = useState(0);
const totalMarks = useMemo(() => {
console.log('Calculating total marks');
return marks.reduce(
(total, mark) => total + mark,
0
);
}, [marks]);
return (
<div>
<h2>Student Marks</h2>
<p>Total Marks: {totalMarks}</p>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase Counter
</button>
</div>
);
}
Expected Output:
Student Marks
Total Marks: 245
Counter: 0
Explanation:
- The marks array contains three student marks.
- reduce() calculates their total.
- useMemo caches the calculated total.
- Changing the counter does not change the marks dependency.
- React can reuse the cached total when the dependency is unchanged.
6. Use useCallback for Function References
The useCallback Hook caches a function reference between renders while its dependencies remain unchanged. This is useful when passing callbacks to memoized child components or when a stable function reference is important to a Hook dependency.
import { memo } from 'react';
const StudentButton = memo(function StudentButton({ onSelect }) {
console.log('StudentButton rendered');
return (
<button onClick={onSelect}>
Select Student
</button>
);
});
export default StudentButton;
import { useCallback, useState } from 'react';
import StudentButton from './StudentButton';
export default function App() {
const [count, setCount] = useState(0);
const selectStudent = useCallback(() => {
console.log('Student selected');
}, []);
return (
<div>
<h2>Student Selection</h2>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase Counter
</button>
<StudentButton onSelect={selectStudent} />
</div>
);
}
Expected Output:
Student Selection
Counter: 0
The selectStudent callback keeps the same reference while its dependencies remain unchanged.
Explanation:
- useCallback creates a memoized callback reference.
- The callback has no dependencies in this example.
- The child receives the same callback reference on later renders.
- React.memo can skip rendering the child when its props are unchanged.
7. Use Lazy Loading and Code Splitting
Large React applications may contain components that users do not need immediately. Lazy loading allows selected components to load when they are rendered, helping reduce the initial JavaScript bundle when used appropriately.
export default function Reports() {
return (
<div>
<h3>Student Reports</h3>
<p>View student performance reports.</p>
</div>
);
}
import { lazy, Suspense } from 'react';
const Reports = lazy(() => import('./Reports'));
export default function App() {
return (
<div>
<h2>Student Dashboard</h2>
<Suspense fallback={<p>Loading reports...</p>}>
<Reports />
</Suspense>
</div>
);
}
Expected Output:
Student Dashboard
View student performance reports.
The loading message can appear while the Reports module is loading. After it loads, React displays the Reports component.
Explanation:
- lazy() dynamically imports the Reports component.
- Suspense defines the fallback UI while the component loads.
- The Reports component is loaded when React needs to render it.
- Code splitting can reduce the initial JavaScript bundle.
8. Optimize Large Lists
Rendering thousands of list items can increase browser rendering work and affect scrolling performance. Stable keys, pagination, and list virtualization can help address different list-related performance problems.
const students = [
{ id: 1, name: 'Samadhan' },
{ id: 2, name: 'Samiksha' },
{ id: 3, name: 'Rahul' },
{ id: 4, name: 'Priya' }
];
export default function StudentList() {
const visibleStudents = students.slice(0, 3);
return (
<div>
<h2>Student List</h2>
<ul>
{visibleStudents.map((student) => (
<li key={student.id}>
{student.name}
</li>
))}
</ul>
</div>
);
}
Expected Output:
Student List
- Samadhan
- Samiksha
- Rahul
Explanation:
- slice(0, 3) selects the first three student records.
- map() converts the selected records into list elements.
- Each item uses a stable student ID as its key.
- Very large scrolling lists may benefit from virtualization.
9. Keep State Close to Where It Is Used
State should generally be placed in the lowest component that needs to manage it. This is called state colocation. It can help prevent unrelated parts of the component tree from rendering because of state changes they do not need.
State Colocation Example
Keep search state inside the Search Component when other components do not need that state.
import { useState } from 'react';
export default function StudentSearch() {
const [search, setSearch] = useState('');
return (
<div>
<h3>Search Students</h3>
<input
type="text"
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Enter student name"
/>
<p>Search: {search}</p>
</div>
);
}
Explanation:
- The search state belongs to StudentSearch.
- Typing in the input updates the local state.
- The component that needs the search value can access it directly.
- State can be lifted up if multiple components need to share it.
10. Avoid Unnecessary Effects
The useEffect Hook is intended for synchronizing React components with external systems. It is generally unnecessary to use an Effect merely to calculate a value from existing state or props.
import { useEffect, useState } from 'react';
function StudentName() {
const [firstName, setFirstName] = useState('Samadhan');
const [lastName, setLastName] = useState('Patil');
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);
return <h3>{fullName}</h3>;
}
import { useState } from 'react';
export default function StudentName() {
const [firstName, setFirstName] = useState('Samadhan');
const [lastName, setLastName] = useState('Patil');
const fullName = firstName + ' ' + lastName;
return (
<div>
<h3>{fullName}</h3>
</div>
);
}
Expected Output:
Samadhan Patil
Explanation:
- firstName and lastName store the original state values.
- fullName is calculated directly during rendering.
- An additional state variable is not required for fullName.
- A derived value avoids an unnecessary Effect-driven state update.
11. Optimize API Requests and Assets
Application performance depends not only on component rendering but also on network requests, images, fonts, and the amount of JavaScript and data downloaded by the browser.
Efficient API Requests
Fetch only the records required for the current page. Use pagination and server-side filtering for large datasets.
Optimized Images
Use suitable image dimensions, responsive images, and efficient image formats to reduce download size.
Appropriate Caching
Reuse cached data when appropriate and handle stale data and invalidation correctly.
Loading and Error States
Display clear feedback while data loads and when an API request fails.
12. Measure Performance with React Developer Tools
React Developer Tools provides the Components and Profiler panels. The Profiler helps developers inspect component rendering activity and identify components that may be doing unnecessary work.
Performance Profiling Process
How it works:
- Open the Profiler panel in React Developer Tools.
- Record an interaction that feels slow.
- Inspect the components that rendered during the interaction.
- Determine whether the rendering was necessary.
- Apply an appropriate optimization and compare the results.
13. Comparison of React Performance Techniques
| Technique | Purpose | When to Use |
|---|---|---|
| React.memo | Can skip rendering when props are unchanged. | Expensive child components with stable props. |
| useMemo | Caches a calculated value. | Expensive calculations with suitable dependencies. |
| useCallback | Caches a function reference. | When callback identity affects memoization or dependencies. |
| Lazy Loading | Loads selected component code when needed. | Large routes and components. |
| Pagination | Displays a limited set of records per page. | Large tables and record collections. |
| Virtualization | Limits the number of mounted list items. | Very large scrolling lists. |
| State Colocation | Keeps state close to the components using it. | State used by only a small part of the UI. |
| React Profiler | Helps inspect rendering behavior. | Identifying and verifying performance bottlenecks. |
14. Common Performance Optimization Mistakes
- Memoizing everything: React.memo, useMemo, and useCallback can add complexity without improving performance in simple cases.
- Using unstable keys: Array indexes can be unsuitable when items are inserted, removed, or reordered.
- Ignoring object references: New object and function references can prevent memoized components from skipping renders.
- Using Effects unnecessarily: Derived values can often be calculated directly from existing state or props.
- Loading every component immediately: Large applications may benefit from code splitting.
- Rendering too many list items: Pagination or virtualization may be appropriate for large lists.
- Optimizing without measurement: Profile the application instead of relying on assumptions.
15. React Performance Best Practices
- Build small, focused, and reusable components.
- Use stable, unique keys when rendering lists.
- Apply React.memo when skipping expensive renders is beneficial.
- Use useMemo for expensive calculations when appropriate.
- Use useCallback when function identity matters.
- Apply lazy loading to suitable large components and routes.
- Use pagination or virtualization for large lists when appropriate.
- Keep state close to the components that need it.
- Avoid unnecessary Effects and duplicated derived state.
- Optimize API requests, images, and JavaScript bundles.
- Use React Developer Tools to identify rendering bottlenecks.
- Measure improvements and verify behavior after optimization.
16. Practice Tasks
- Create a StudentDashboard component containing StudentProfile, StudentCourses, and StudentResults.
- Use React.memo to optimize an expensive StudentDetails component and observe when it renders.
- Build a marks calculator and use useMemo to cache an expensive calculation.
- Pass a callback to a memoized child and use useCallback to preserve its reference when appropriate.
- Load a Reports component using React.lazy and Suspense.
- Create a list of 1,000 student records and compare normal rendering with pagination or virtualization.
- Move a search input's state into its own component and observe how the component tree responds to updates.
- Use React Developer Tools Profiler to identify a rendering bottleneck and verify an optimization.
- Review an existing React application and identify unnecessary Effects, repeated API requests, and oversized assets.
Summary
React performance best practices include creating small and reusable components, avoiding unnecessary renders, using React.memo, useMemo, and useCallback when beneficial, loading large components efficiently, optimizing large lists, keeping state close to where it is used, and avoiding unnecessary Effects. Efficient API requests and optimized assets also contribute to application responsiveness. React Developer Tools helps identify rendering bottlenecks and verify improvements. Always measure performance before and after optimization, select techniques according to the actual problem, and maintain clean and reliable application code.