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

Effect Dependencies and Cleanup

Learn how dependency arrays control when Effects run and how cleanup functions remove event listeners, clear timers, and release resources when they are no longer needed.

1. What Are Effect Dependencies?

Effect dependencies are values listed in the dependency array of the useEffect Hook. React compares these values between renders to determine whether an Effect needs to run again.

Dependencies may include state variables, props, and other reactive values used by the Effect.

Remember: The dependency array should include the reactive values used by the Effect. Do not omit dependencies simply to prevent the Effect from running again.

2. Types of Dependency Arrays

Without a Dependency Array

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

The Effect runs after every committed render.

With an Empty Dependency Array

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

The Effect runs after the initial commit. In development Strict Mode, React may run an additional setup and cleanup cycle.

With a Dependency

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

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

3. How Dependencies Work

React checks the dependency values after rendering. If a dependency changes, React runs the previous cleanup, when provided, and then executes the Effect again.

Component Renders
→
Compare Dependencies
→
Cleanup if Needed
→
Run Effect
Important: React compares dependency values using Object.is. An Effect does not automatically run again when unrelated state changes if its dependencies remain the same.

4. Example: useEffect with Dependencies

This example updates the browser tab title whenever the counter value 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 Application</h2>

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

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

export default App;

Expected Output

Counter Application

Initially: Count: 0

After one click: Count: 1

After two clicks: Count: 2

The browser tab title changes to match the current count.

Explanation: The dependency array contains count. When count changes, the Effect runs again and synchronizes the browser tab title with the latest counter value.

5. What Is Effect Cleanup?

Cleanup is a function returned by useEffect. It reverses or removes the work performed by the Effect setup when that work is no longer needed.

Cleanup is useful for:

  • Removing event listeners.
  • Clearing timers and intervals.
  • Unsubscribing from external services.
  • Aborting or ignoring outdated asynchronous requests.
Remember: React runs cleanup before re-running an Effect whose dependencies changed and when the component is removed.

6. Example: Event Listener Cleanup

This example registers a window resize event listener and removes it during cleanup.

Example Code

import { useEffect } from "react";

function App() {
    useEffect(() => {
        function handleResize() {
            console.log(
                "Window width:",
                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 open the console.

Example console message:

Window width: 1200

The number depends on the actual browser window width.

Explanation: The Effect registers the resize listener. Its cleanup function removes the same listener so that it does not remain registered after the component is removed.

7. Example: Clearing an Interval

An interval continues running until it is cleared. We can return a cleanup function to clear the interval when the component is removed.

Example Code

import { useEffect } from "react";

function App() {
    useEffect(() => {
        const timerId = setInterval(() => {
            console.log("Timer running");
        }, 1000);

        return () => {
            clearInterval(timerId);
        };
    }, []);

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

export default App;

Expected Output

Timer Example

Timer running

Timer running

Timer running

The message is logged approximately every second while the Effect is active.

Explanation: setInterval repeatedly executes the callback. The cleanup function calls clearInterval with the saved timer ID to stop further executions.

8. Important Points

  • Include all reactive values used by an Effect in its dependency array.
  • An omitted dependency array causes the Effect to run after every committed render.
  • An empty dependency array means the Effect does not re-run because of changing reactive dependencies.
  • Cleanup runs before an Effect re-runs and when the component is removed.
  • Use clearInterval to stop an interval and removeEventListener to remove an event listener.
  • Avoid unnecessary Effects for values that can be calculated directly during rendering.

9. Practice Tasks

Complete the following exercises:

  1. Create an Effect that logs a message after every committed render.
  2. Create an Effect that updates the browser tab title when a counter changes.
  3. Compare an empty dependency array with an omitted dependency array.
  4. Register a window resize listener and remove it using cleanup.
  5. Create an interval that logs a message every second and clears the interval during cleanup.
  6. Explain when React runs an Effect cleanup function.

Summary

Effect dependencies determine when a useEffect Hook needs to run again, based on the reactive values used by the Effect. An empty dependency array prevents re-running due to changing dependencies, while omitting the array makes the Effect run after every committed render. Cleanup functions remove event listeners, clear timers, and release resources before an Effect is repeated or when a component is removed. Correct dependency management and cleanup help developers build reliable React applications at CIIT Training Institute.