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

Lazy Loading Components

Learn how to load React components only when they are needed, reduce the initial JavaScript loading cost, and improve the performance of React applications using React.lazy and Suspense.

1. Introduction to Lazy Loading

Lazy loading is a technique in which a component or resource is loaded only when it is required. Instead of loading every component immediately when an application starts, we can load selected components when the user needs them.

Consider a student management application that contains a dashboard, reports page, student details page, and settings page. A student who opens the dashboard may not immediately need the reports or settings components.

Lazy loading helps separate these components into smaller loading units so that some code can be downloaded when required.

Key concept: Lazy loading can reduce the amount of JavaScript needed for the initial screen. It does not necessarily reduce the total size of the application; it changes when different code is loaded.

2. Why Do We Need Lazy Loading?

Faster Initial Loading

The browser may need to download and process less application code before displaying the initial screen.

Smaller Initial Bundle

Separating code into chunks can reduce the size of the JavaScript required at startup.

On-Demand Loading

Less frequently used components can load when the user navigates to the relevant feature.

Better Scalability

Large applications can organize features into separate loading units.

3. Understanding React.lazy

React provides the lazy function to defer loading a component's code until React first attempts to render that component. The component must be loaded through a dynamic import that resolves to a default export.

Syntax
import { lazy, Suspense } from 'react';

const MyComponent = lazy(() => import('./MyComponent'));

function App() {
    return (
        <Suspense fallback={<p>Loading...</p>}>
            <MyComponent />
        </Suspense>
    );
}

export default App;

Explanation:

  • lazy() declares a component that React loads on demand.
  • import() dynamically loads the component module.
  • Suspense displays fallback content while the lazy component is loading.
  • fallback can contain a loading message, spinner, or skeleton UI.
The component returned by React.lazy expects the imported module to provide the component as its default export.

4. Creating a Component Without Lazy Loading

First, consider a normal component import. The imported component becomes part of the application's normal module dependency graph. Depending on the build configuration, it may be included in the initial bundle.

Reports.jsx
export default function Reports() {
    return (
        <div>
            <h2>Reports Page</h2>
            <p>View student performance reports.</p>
        </div>
    );
}
App.jsx
import Reports from './Reports';

export default function App() {
    return (
        <div>
            <h1>CIIT Training Institute</h1>
            <Reports />
        </div>
    );
}

In this example, Reports is imported normally. If the component is part of the initial bundle, its code must be downloaded before that bundle can be used. The exact bundling behavior depends on the build tool and configuration.

5. Implementing Lazy Loading

We can update the previous example to load the Reports component on demand by using React.lazy and Suspense.

App.jsx
import { lazy, Suspense, useState } from 'react';

const Reports = lazy(() => import('./Reports'));

export default function App() {
    const [showReports, setShowReports] = useState(false);

    return (
        <div>
            <h1>CIIT Training Institute</h1>

            <button onClick={() => setShowReports(true)}>
                Open Reports
            </button>

            {showReports && (
                <Suspense fallback={<p>Loading reports...</p>}>
                    <Reports />
                </Suspense>
            )}
        </div>
    );
}

How it works:

  1. The application initially displays the heading and button.
  2. The Reports component is not rendered initially.
  3. When the user clicks Open Reports, the state changes.
  4. React attempts to render Reports and loads its module if needed.
  5. Suspense displays the fallback while the component is loading.
  6. When the module is ready, React displays the Reports component.

6. Understanding Suspense

Suspense lets you specify fallback content while a supported child is waiting for something, such as a lazy-loaded component module. It provides a convenient way to display loading feedback instead of leaving an empty area.

SuspenseExample.jsx
import { lazy, Suspense } from 'react';

const StudentDetails = lazy(
    () => import('./StudentDetails')
);

export default function SuspenseExample() {
    return (
        <div>
            <h2>Student Management</h2>

            <Suspense
                fallback={<p>Loading student details...</p>}
            >
                <StudentDetails />
            </Suspense>
        </div>
    );
}

While StudentDetails is loading, the fallback message can be displayed. After the module is ready, React displays the component.

Important: Suspense handles the loading state for supported operations. It is not, by itself, a complete error-handling solution for failed dynamic imports. Use an appropriate Error Boundary to handle rendering and loading errors.

7. Lazy Loading with React Router

In larger applications, different routes often represent separate features. Lazy loading route components can allow each feature's code to be loaded when a user navigates to that route.

App.jsx
import { lazy, Suspense } from 'react';
import {
    BrowserRouter,
    Routes,
    Route,
    Link
} from 'react-router-dom';

const Home = lazy(() => import('./pages/Home'));
const Reports = lazy(() => import('./pages/Reports'));

export default function App() {
    return (
        <BrowserRouter>
            <nav>
                <Link to="/">Home</Link>
                {' | '}
                <Link to="/reports">Reports</Link>
            </nav>

            <Suspense fallback={<p>Loading page...</p>}>
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route
                        path="/reports"
                        element={<Reports />}
                    />
                </Routes>
            </Suspense>
        </BrowserRouter>
    );
}

In this example, Home and Reports are lazy-loaded route components. A user who visits the Home route does not necessarily need to download the Reports component code immediately.

This example assumes React Router is installed and that ./pages/Home and ./pages/Reports each have a default export.

8. Lazy Loading vs Normal Imports

Feature Normal Import Lazy Loading
Import style Static import Dynamic import through React.lazy
Loading behavior Depends on how the build bundles the module Module loading is deferred until the component is first rendered
Loading fallback Not provided by the import itself Suspense can display fallback content
Common use Components needed immediately Large or less frequently used components
Initial bundle May include the imported module Can move the module into a separate chunk

9. Common Mistakes

  • Forgetting Suspense: A lazy component needs an appropriate Suspense boundary above it.
  • Missing default export: React.lazy expects the imported module to resolve to an object whose default export is the component.
  • Lazy loading everything: Components needed immediately may not benefit from deferred loading.
  • Ignoring loading feedback: A suitable fallback helps users understand that content is loading.
  • Ignoring import failures: Use an Error Boundary or another suitable error-handling strategy for failed component loading.
  • Creating lazy components repeatedly: Declare lazy components outside the rendering component so their identity remains stable.

10. Best Practices

  • Lazy-load large features that are not required for the initial screen.
  • Use Suspense with a meaningful loading message or skeleton.
  • Consider route-level code splitting for large applications.
  • Keep lazy component declarations outside the parent component's render function.
  • Handle loading failures with an appropriate error-handling strategy.
  • Measure the initial bundle size and loading experience before and after code splitting.

11. Practice Tasks

  1. Create a Reports component and import it normally into App.jsx.
  2. Convert the Reports component to use React.lazy.
  3. Wrap the lazy component with Suspense and display a loading message.
  4. Use a button to load the Reports component only when requested.
  5. Create Home and Reports routes and lazy-load both pages.
  6. Compare the application's initial loading behavior before and after code splitting.

Summary

Lazy loading allows React applications to defer loading selected components until they are required. React.lazy works with dynamic imports, while Suspense provides fallback content during loading. Lazy loading can reduce the JavaScript needed for the initial screen, especially when used for large features or route components. Selecting appropriate components, providing loading feedback, handling failures, and measuring the result are important parts of an effective implementation.