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

useEffect Hook

Learn how to use the useEffect Hook to synchronize React components with external systems, respond to state changes, and perform operations such as fetching data and managing browser events.

1. What Is the useEffect Hook?

The useEffect Hook is a built-in React Hook that allows functional components to synchronize with external systems. It can be used for operations such as fetching data from an API, subscribing to events, and working with timers.

An Effect runs after React commits a render. Depending on its dependency array, it can run after the initial mount and again when specified dependencies change.

Remember: Import useEffect from React before using it. Effects are intended for synchronizing with external systems, not for every calculation performed during rendering.

2. Syntax of useEffect

The basic syntax is:

useEffect(() => {
    // Effect logic

    return () => {
        // Optional cleanup logic
    };
}, [dependencies]);
  • Effect function: Contains the operation that React should synchronize.
  • Cleanup function: Optionally removes subscriptions, clears timers, or reverses setup work.
  • Dependency array: Specifies the reactive values that determine when the Effect should run again.

3. How useEffect Works

React renders the component and commits the changes. After that, the Effect runs when required by its dependencies.

Component Render
→
React Commits UI
→
Effect Runs
→
External System Sync
Important: When dependencies change, React runs the previous cleanup function, if provided, before running the Effect again. React also runs cleanup when the component is removed.

4. Basic Example of useEffect

In this example, the Effect runs after the component commits its initial render because the dependency array is empty.

Example Code

import { useEffect } from "react";

function App() {
    useEffect(() => {
        console.log("Component rendered");
    }, []);

    return (
        <div>
            <h2>useEffect Example</h2>
            <p>Open the browser console.</p>
        </div>
    );
}

export default App;

Expected Output

useEffect Example

Open the browser console.

Console message after the initial Effect runs:

Component rendered
Explanation: The empty dependency array [] means this Effect does not re-run because of changes to reactive dependencies. In development Strict Mode, React may run an additional setup and cleanup cycle to help detect problems.

5. useEffect with a Dependency

We can provide a state variable in the dependency array. The Effect then runs after the initial commit and again whenever that dependency changes.

Example Code

import { useEffect, useState } from "react";

function App() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        document.title = `Count: ${count}`;
    }, [count]);

    return (
        <div>
            <h2>Counter Example</h2>

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

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

export default App;

Expected Output

Initially, the page displays:

Count: 0

After clicking Increase:

Count: 1

The browser tab title changes to Count: 1.

Explanation: The count state is included in the dependency array. Whenever count changes, React runs the Effect again and updates the browser tab title.

6. Understanding the Dependency Array

Without a Dependency Array

useEffect(() => {
    console.log("Effect executed");
});

The Effect runs after every committed render. If the Effect updates state on every render without a suitable condition, it can cause repeated rendering.

With an Empty Dependency Array

useEffect(() => {
    console.log("Initial Effect");
}, []);

The Effect runs after the initial commit. Development Strict Mode may perform an extra setup and cleanup cycle.

With a Dependency

useEffect(() => {
    console.log("Count changed:", count);
}, [count]);

The Effect runs after the initial commit and again when the value of count changes.

Remember: Include the reactive values used by your Effect in its dependency array. The dependency list should match the values the Effect reads from the component.

7. Why Is Effect Cleanup Important?

Some Effects create resources that must be released. For example, a timer, event listener, or subscription may continue working even when it is no longer needed. Cleanup helps prevent unnecessary work and resource leaks.

Example Code

import { useEffect } from "react";

function App() {
    useEffect(() => {
        function handleResize() {
            console.log(window.innerWidth);
        }

        window.addEventListener(
            "resize",
            handleResize
        );

        return () => {
            window.removeEventListener(
                "resize",
                handleResize
            );
        };
    }, []);

    return (
        <div>
            <h2>Window Resize Example</h2>
            <p>Resize the browser window and check
                the console.</p>
        </div>
    );
}

export default App;

Expected Output

Window Resize Example

Resize the browser window and check the console to see the current window width.

Explanation: The Effect registers a resize event listener. The returned cleanup function removes that listener when the component is removed, or before the Effect is set up again.

8. Important Points About useEffect

  • Import useEffect from React.
  • Call Hooks at the top level of a component or custom Hook.
  • Use the dependency array to control when an Effect needs to synchronize again.
  • Return a cleanup function when setup creates something that must be released.
  • Avoid updating state unnecessarily inside an Effect, as it may trigger additional renders.
  • Use Effects for synchronization with external systems, such as event listeners, subscriptions, and network APIs.

9. Practice Tasks

Complete these exercises to practise the useEffect Hook:

  1. Create a component that logs a message after its initial render.
  2. Create a counter that updates the browser tab title whenever the count changes.
  3. Create an Effect that logs a message when a selected course changes.
  4. Register a window resize event listener and remove it using a cleanup function.
  5. Compare an Effect with an empty dependency array and an Effect without a dependency array.

Summary

The useEffect Hook allows React functional components to synchronize with external systems after a render has been committed. Its dependency array determines when an Effect should run again, while an optional cleanup function removes event listeners, clears timers, or releases other resources. The Hook is useful for tasks such as updating the browser tab title, managing subscriptions, and fetching data from APIs. Understanding dependencies and cleanup helps developers build reliable React applications at CIIT Training Institute.