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

Optimizing Large Lists

Learn how to improve the performance of React applications that display large amounts of data by using stable keys, React.memo, efficient list rendering, and list virtualization.

1. Introduction to Large Lists

React applications frequently display lists of students, products, employees, transactions, and other records. When a list contains only a few items, rendering it is usually straightforward. However, rendering thousands of items can increase rendering work and affect scrolling performance.

For example, a student management application may contain thousands of student records. Rendering every record at once can create a large component tree, even when the user can see only a small portion of the list on the screen.

React provides several techniques that help developers optimize list rendering. These include using stable keys, avoiding unnecessary renders, and rendering only the visible portion of very large lists.

Key concept: The best optimization depends on the list size, item complexity, and actual performance bottleneck. Measure the application before selecting an optimization technique.

2. Understanding List Rendering

React commonly uses the JavaScript map() method to convert an array of data into a collection of components or elements.

StudentList.jsx
const students = [
    { id: 1, name: 'Samadhan' },
    { id: 2, name: 'Samiksha' },
    { id: 3, name: 'Rahul' }
];

export default function StudentList() {
    return (
        <div>
            <h2>Student List</h2>

            {students.map((student) => (
                <p key={student.id}>
                    {student.name}
                </p>
            ))}
        </div>
    );
}

How it works:

  • The students array contains the student records.
  • The map() method processes each record.
  • React creates an element for every student.
  • The key property helps React identify each item between updates.

3. Why Can Large Lists Become Slow?

Many Elements

Creating thousands of elements can increase the amount of rendering work.

Complex Components

Each item may contain several components, calculations, and event handlers.

Frequent Updates

State changes can cause list components to render again when their inputs change.

DOM Size

A large number of mounted elements can increase browser layout, painting, and memory costs.

4. Using Stable Keys

When rendering a list, React uses the key prop to match items between renders. A stable and unique key helps React determine which items were added, removed, or reordered.

IncorrectList.jsx
function StudentList({ students }) {
    return (
        <ul>
            {students.map((student, index) => (
                <li key={index}>
                    {student.name}
                </li>
            ))}
        </ul>
    );
}

Using the array index as a key can cause problems when items are inserted, deleted, or reordered because an index identifies a position rather than the actual record.

ImprovedList.jsx
function StudentList({ students }) {
    return (
        <ul>
            {students.map((student) => (
                <li key={student.id}>
                    {student.name}
                </li>
            ))}
        </ul>
    );
}
Remember: Prefer a stable, unique identifier from the data, such as student.id. Keys help React reconcile lists correctly; they do not, by themselves, prevent components from rendering.

5. Avoiding Unnecessary Renders with React.memo

If a list item component is expensive to render, React.memo can help skip its render when its props remain unchanged according to React's default prop comparison.

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

const StudentItem = memo(function StudentItem({ student }) {
    console.log('Rendering:', student.name);

    return (
        <li>
            <strong>{student.name}</strong>
            <p>Course: {student.course}</p>
        </li>
    );
});

export default StudentItem;
StudentList.jsx
import { useState } from 'react';
import StudentItem from './StudentItem';

const initialStudents = [
    { id: 1, name: 'Samadhan', course: 'React' },
    { id: 2, name: 'Samiksha', course: 'Java' },
    { id: 3, name: 'Rahul', course: 'SQL' }
];

export default function StudentList() {
    const [count, setCount] = useState(0);

    return (
        <div>
            <h2>Student Dashboard</h2>

            <p>Counter: {count}</p>

            <button onClick={() => setCount(count + 1)}>
                Increase Counter
            </button>

            <ul>
                {initialStudents.map((student) => (
                    <StudentItem
                        key={student.id}
                        student={student}
                    />
                ))}
            </ul>
        </div>
    );
}

When the counter changes, the parent renders again. Because the student records in this example retain the same object references and the StudentItem props remain unchanged, React.memo can skip rendering those items.

Important: If you recreate every student object on each parent render, the object props will have new references and the default React.memo comparison may not skip those renders.

6. Using Pagination

Pagination divides a large dataset into smaller pages. Instead of displaying every record at once, the application displays a limited number of records and allows the user to move between pages.

PaginatedStudentList.jsx
import { useState } from 'react';

const students = Array.from(
    { length: 100 },
    (_, index) => ({
        id: index + 1,
        name: `Student ${index + 1}`
    })
);

const PAGE_SIZE = 10;

export default function PaginatedStudentList() {
    const [page, setPage] = useState(0);

    const startIndex = page * PAGE_SIZE;
    const visibleStudents = students.slice(
        startIndex,
        startIndex + PAGE_SIZE
    );

    const totalPages = Math.ceil(
        students.length / PAGE_SIZE
    );

    return (
        <div>
            <h2>Student Records</h2>

            <ul>
                {visibleStudents.map((student) => (
                    <li key={student.id}>
                        {student.name}
                    </li>
                ))}
            </ul>

            <p>
                Page {page + 1} of {totalPages}
            </p>

            <button
                disabled={page === 0}
                onClick={() => setPage(page - 1)}
            >
                Previous
            </button>

            <button
                disabled={page === totalPages - 1}
                onClick={() => setPage(page + 1)}
            >
                Next
            </button>
        </div>
    );
}

Explanation:

  • PAGE_SIZE determines how many records appear on one page.
  • The slice() method selects the records for the current page.
  • The Previous and Next buttons update the page state.
  • Only the current page's records are rendered in the list.
This example uses an in-memory array. For a large database, pagination can also be implemented on the server so that the client receives only the records needed for the requested page.

7. List Virtualization

List virtualization is a technique that renders only the items currently visible in a scrolling area, together with a small number of nearby items. The rest of the list is not mounted until it is needed.

For example, a list may contain 10,000 student records, but only about 20 records may fit inside the visible scrolling area. Virtualization avoids mounting all 10,000 rows at the same time.

How Virtualization Works

Student 1
Student 2
Student 3
Student 4
Student 5
Student 6
Student 7
Student 8

Only the visible rows and a small buffer need to be mounted.

Libraries such as react-window can help implement virtualized lists. Their APIs differ by library and version, so select an implementation compatible with your project.

Pagination and virtualization solve different problems. Pagination displays a limited page of records, while virtualization limits how many list items are mounted in a scrolling view.

8. Choosing the Right Optimization

Technique Purpose Useful When
Stable Keys Help React identify list items between updates. Every rendered list.
React.memo Can skip item renders when props are unchanged. Expensive items receiving stable props.
Pagination Displays a limited number of records per page. Large tables and searchable record collections.
Virtualization Mounts only visible items and a small buffer. Very large scrolling lists.
Server-side Pagination Fetches only a subset of records from the server. Datasets too large to send to the browser at once.

9. Common Mistakes

  • Using unstable keys: Array indexes can be unsuitable when records are inserted, removed, or reordered.
  • Assuming keys prevent renders: Keys help reconciliation; they are not a memoization mechanism.
  • Memoizing everything: Memoization has overhead and may not improve simple list items.
  • Rendering too many rows: Large lists may benefit from pagination or virtualization.
  • Ignoring object references: Newly created object props can prevent React.memo from skipping a render.
  • Fetching every database record: Large datasets may need server-side pagination or filtering.

10. Best Practices

  • Use stable, unique keys for every item in a rendered list.
  • Keep list item components focused and easy to maintain.
  • Use React.memo when profiling shows repeated expensive renders can be skipped.
  • Use pagination when users need to browse a large collection in manageable sections.
  • Consider virtualization for very large scrolling lists.
  • Use server-side filtering and pagination for large remote datasets.
  • Measure rendering and scrolling performance before and after optimization.

11. Practice Tasks

  1. Create a student list using the map() method and stable student IDs.
  2. Build a list containing 1,000 sample student records.
  3. Wrap an expensive StudentItem component with React.memo and compare rendering behavior.
  4. Implement pagination with 10 records per page.
  5. Research and implement list virtualization using a compatible React library.
  6. Compare the behavior and performance of a normal list, a paginated list, and a virtualized list.

Summary

Optimizing large React lists involves choosing efficient rendering strategies for the amount of data and the complexity of each item. Stable keys help React reconcile list items, React.memo can avoid some unnecessary renders, pagination limits the records displayed at one time, and virtualization limits the number of mounted rows. For very large datasets, server-side pagination and filtering can also reduce the amount of data transferred to the browser. Measure the application's behavior to select the most effective approach.