Master React From Scratch

Clear, practical, and structured React lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to React
Introduction to React What Is React? Features of React Advantages of React Limitations of React Uses of React React vs JavaScript React Architecture
2. React Getting Started
Getting Started Introduction Prerequisites Installing Node.js and npm Creating a React Project with Vite React Project Structure Running React Application Your First React Application
3. JSX
JSX Introduction What Is JSX? JavaScript Expressions JSX Attributes Rendering JSX Elements JSX Children React Fragments JSX Rules and Best Practices JSX vs HTML
4. React Components
Components Introduction Functional Components Class Components Component Composition Reusable Components Component Tree Component Lifecycle Import and Export Components
5. React Props
Props Introduction What Are Props? Passing Props to Components Props Destructuring Default Props Values Children Props Typing Props with TypeScript Props vs State
6. React State
State Introduction What Is State? useState Hook Updating State Functional State Updates State with Objects State with Arrays State Immutability Lifting State Up
7. React Events
Events Introduction Handling Events Passing Arguments to Event Handlers Synthetic Events Form Events Keyboard and Mouse Events Event Propagation
8. Conditional Rendering
Conditional Rendering Introduction If-Else Rendering Ternary Operator Logical AND Operator Element Variables Preventing Rendering Multiple Conditions Conditional CSS Classes
9. Lists and Keys
Lists and Keys Introduction Rendering Lists with map() Understanding Keys Choosing Unique Keys Lists of Objects Filtering Lists Sorting Lists Empty Lists and Conditional Rendering
10. React Forms
Forms Introduction Handling Forms Controlled Components Uncontrolled Components Handling Input Fields Checkboxes and Radio Buttons Select and Textarea Form Validation Form Submission
11. React Hooks
Hooks Introduction useState Hook useEffect Hook Effect Dependencies and Cleanup useRef Hook useReducer Hook useMemo Hook useCallback Hook Custom Hooks Rules of Hooks
12. React Context API
Context API Introduction createContext useContext Context Provider Reading Context Updating Context Using Multiple Contexts Context API vs Props Context API Best Practices
13. React Routing
Routing Introduction Introduction to React Router Installing React Router BrowserRouter Setup Routes and Route Components Link and NavLink Programmatic Navigation URL Parameters and useParams Nested Routes Not Found Routes Protected Routes
14. API Integration
API Integration Introduction Fetch API Async/Await with API Calls Displaying API Data Loading and Error States Sending POST Requests API Error Handling Using Axios Custom Fetch Hook API Environment Variables
15. State Management
State Management Introduction Global State Prop Drilling Introduction to Redux Redux Core Concepts Redux Toolkit Store and Slices useSelector and useDispatch Async Operations with Redux Toolkit State Management Best Practices
16. React Performance
Performance Introduction Understanding Re-Renders Avoiding Unnecessary Re-Renders React.memo useMemo Optimization useCallback Optimization React Developer Tools and Profiler Lazy Loading Components Code Splitting Optimizing Large Lists Performance Best Practices

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.

Key concept: Optimize actual performance problems instead of applying every optimization technique to every component. Measure performance before and after making changes.

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

Identify a Performance Problem
↓
Measure Rendering Performance
↓
Choose an Appropriate Technique
↓
Implement the Optimization
↓
Measure and Compare Again

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.
Performance optimization is a process of measuring, improving, and verifying—not simply adding memoization everywhere.

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.

StudentDashboard.jsx
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

Student Profile

Name: Samadhan

Student Courses

React Development

Student Results

Marks: 90

Explanation:

  • StudentProfile displays student information.
  • StudentCourses displays the enrolled course.
  • StudentResults displays the student's result.
  • StudentDashboard combines the smaller components.
Smaller components improve organization and reusability. However, splitting components does not automatically guarantee faster rendering; measure performance when necessary.

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.

StudentDetails.jsx
import { memo } from 'react';

const StudentDetails = memo(function StudentDetails({ name }) {
    console.log('StudentDetails rendered');

    return (
        <div>
            <h3>Student: {name}</h3>
        </div>
    );
});

export default StudentDetails;
App.jsx
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

Student: Samadhan

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.
Important: React.memo uses shallow prop comparison by default. New object, array, or function references can prevent a memoized component from skipping a render. React.memo is a performance optimization, not a guarantee that a component will never render again.

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.

StudentMarks.jsx
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.
Use useMemo when a calculation is expensive enough to justify caching. Simple calculations usually do not need it.

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.

StudentButton.jsx
import { memo } from 'react';

const StudentButton = memo(function StudentButton({ onSelect }) {
    console.log('StudentButton rendered');

    return (
        <button onClick={onSelect}>
            Select Student
        </button>
    );
});

export default StudentButton;
App.jsx
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.
useCallback does not automatically make every function faster. Use it when function identity matters for memoization or dependency management.

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.

Reports.jsx
export default function Reports() {
    return (
        <div>
            <h3>Student Reports</h3>
            <p>View student performance reports.</p>
        </div>
    );
}
App.jsx
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

Loading reports...
Student Reports

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.
Lazy loading is particularly useful for large routes, dashboards, reports, and features that are not required immediately.

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.

StudentList.jsx
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.
Pagination limits the records displayed on a page, while virtualization limits how many list items are mounted in a scrolling view. For large remote datasets, server-side pagination can also reduce the amount of data transferred.

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

Student Dashboard
↓
Student Profile
Search Component

Keep search state inside the Search Component when other components do not need that state.

StudentSearch.jsx
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.
Do not move every state variable into the root component. Keep shared state at the nearest common parent that needs 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.

AvoidUnnecessaryEffect.jsx
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>;
}
StudentName.jsx — Improved
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.
Effects are still important when synchronizing with external systems, subscriptions, or network-related behavior. Avoid only the Effects that are unnecessary for the task.

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.

Avoid repeatedly making identical unnecessary requests. Choose caching and data-fetching strategies based on the application's requirements.

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

Open React Developer Tools
↓
Record a User Interaction
↓
Inspect Component Rendering
↓
Identify the Bottleneck
↓
Optimize and Record Again

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.
Development builds can behave differently from production builds. For meaningful performance comparisons, also test a production build under realistic conditions.

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.
Good performance practices should improve responsiveness while keeping the application understandable, maintainable, and correct.

16. Practice Tasks

  1. Create a StudentDashboard component containing StudentProfile, StudentCourses, and StudentResults.
  2. Use React.memo to optimize an expensive StudentDetails component and observe when it renders.
  3. Build a marks calculator and use useMemo to cache an expensive calculation.
  4. Pass a callback to a memoized child and use useCallback to preserve its reference when appropriate.
  5. Load a Reports component using React.lazy and Suspense.
  6. Create a list of 1,000 student records and compare normal rendering with pagination or virtualization.
  7. Move a search input's state into its own component and observe how the component tree responds to updates.
  8. Use React Developer Tools Profiler to identify a rendering bottleneck and verify an optimization.
  9. 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.

← Previous: Optimizing Large Lists