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

Code Splitting

Learn how to divide a React application's JavaScript into smaller chunks, load code when required, and improve the initial loading experience using dynamic imports and React.lazy.

1. Introduction to Code Splitting

Code splitting is a technique that divides an application's JavaScript code into smaller files called chunks. Instead of downloading all application code at once, the browser can load the chunks required for the current page and load other chunks when they are needed.

As a React application grows, it may contain many features such as dashboards, reports, student management, settings, and authentication. Loading every feature's code immediately can increase the amount of JavaScript needed during the initial load.

Code splitting helps organize the application's code into smaller loading units. It is commonly implemented through dynamic imports and supported by build tools such as Vite and webpack.

Key concept: Code splitting changes how application code is divided and loaded. It can reduce the initial JavaScript download, but it does not necessarily reduce the total amount of JavaScript in the application.

2. Understanding Code Splitting with a Diagram

Without code splitting, an application may place most of its JavaScript into one large initial bundle. With code splitting, the application can load a smaller initial bundle and separate feature chunks when required.

Without Code Splitting

React Application
↓
One Large JavaScript Bundle
↓
Dashboard + Reports + Settings + Students

Multiple features may be included in the initial JavaScript bundle.

With Code Splitting

React Application
↓
Initial JavaScript Bundle
↓
Dashboard
Reports Chunk
Settings Chunk

Additional feature chunks can be loaded when the application needs them.

3. Why Do We Need Code Splitting?

Smaller Initial Download

The browser may download less JavaScript before displaying the initial screen.

On-Demand Features

Features that are not immediately needed can be loaded when the user opens them.

Better Organization

Separate chunks can correspond to different pages, features, or dependencies.

Performance Optimization

Smaller initial downloads can help improve loading performance, depending on the application and network.

4. Static Imports and Dynamic Imports

Static imports are commonly used for modules that are required by a component. Dynamic imports allow a module to be requested asynchronously and can create a code-splitting point in supported build tools.

Static Import
import Reports from './Reports';

export default function App() {
    return (
        <div>
            <h1>Student Dashboard</h1>
            <Reports />
        </div>
    );
}
Dynamic Import
import('./Reports')
    .then((module) => {
        console.log('Reports module loaded');
        console.log(module.default);
    })
    .catch((error) => {
        console.error('Unable to load Reports', error);
    });

The dynamic import returns a Promise that resolves to the module. Build tools can use this import to create a separate chunk. The code above demonstrates module loading; React.lazy is the usual approach when rendering a lazily loaded React component.

5. Implementing Code Splitting with React.lazy

React.lazy allows a component to be loaded through a dynamic import when React first attempts to render it. Suspense provides fallback content while the component's module is loading.

Reports.jsx
export default function Reports() {
    return (
        <div>
            <h2>Reports Page</h2>
            <p>View student performance reports.</p>
        </div>
    );
}
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 Open Reports is clicked, the state changes.
  4. React attempts to render Reports and requests its module if it has not loaded yet.
  5. Suspense can display Loading reports while the module is loading.
  6. When the module becomes available, React displays the Reports component.

6. Code Splitting with React Router

Large applications often contain multiple routes. Route-based code splitting allows page components to be loaded when users navigate to the corresponding routes.

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'));
const Settings = lazy(() => import('./pages/Settings'));

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

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

Here, Home, Reports, and Settings are declared as lazy-loaded components. A build tool that supports dynamic-import splitting can generate separate chunks for these modules.

This example assumes React Router is installed and each page component provides a default export. The application must also configure its build tool to process dynamic imports correctly.

7. Understanding Suspense and Loading States

When a lazy-loaded component is requested, the browser may need time to download and evaluate its JavaScript. Suspense allows React to display fallback content while the component is waiting to load.

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

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

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

            <Suspense
                fallback={
                    <div className="loading-message">
                        Loading student details...
                    </div>
                }
            >
                <StudentDetails />
            </Suspense>
        </div>
    );
}

The fallback is displayed while the lazy component is waiting for its module. After the module loads successfully, React renders the StudentDetails component.

Important: Suspense provides loading fallback behavior, not complete error handling. Failed lazy imports should be handled using an appropriate Error Boundary or another suitable error strategy.

8. Code Splitting vs Lazy Loading

Feature Code Splitting Lazy Loading
Meaning Dividing application code into separate chunks. Deferring loading until the resource or component is needed.
Purpose Creates smaller loading units. Controls when selected code is requested.
React support Usually configured through dynamic imports and build tools. React.lazy and Suspense support lazy component rendering.
Common use Separating large application features. Loading a feature when a user opens it.
Relationship Creates opportunities to load chunks separately. Can use those chunks on demand.

9. Common Mistakes

  • Splitting every small component: Too many tiny chunks can introduce additional network overhead.
  • Forgetting Suspense: Lazy-loaded components need an appropriate Suspense boundary.
  • Missing default exports: React.lazy expects the imported module's default export to be the component.
  • Ignoring loading feedback: Provide useful fallback content while chunks load.
  • Ignoring import failures: Provide an appropriate error-handling strategy for failed chunk requests.
  • Assuming total code size decreases: Code splitting changes bundle organization and loading behavior, not necessarily total code size.

10. Best Practices

  • Split large features that are not required for the initial screen.
  • Use route-based code splitting for applications with many pages.
  • Use meaningful Suspense fallback content.
  • Keep lazy component declarations outside the rendering component.
  • Handle loading failures appropriately.
  • Measure bundle sizes and loading performance before and after changes.

11. Practice Tasks

  1. Create Home, Reports, and Settings page components.
  2. Import the pages normally and observe the application's build output.
  3. Convert the page imports to React.lazy and use Suspense.
  4. Configure route-based loading with React Router.
  5. Display a fallback message while a page chunk loads.
  6. Compare the initial bundle and generated chunks using your build tool's output.

Summary

Code splitting divides an application's JavaScript into smaller chunks so that the initial screen does not always need every feature's code. Dynamic imports and supported build tools create opportunities for separate chunks, while React.lazy and Suspense help load components when they are required and display fallback content during loading. Route-based splitting, meaningful loading states, appropriate error handling, and performance measurement help developers apply code splitting effectively.