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

API Integration with Custom Hooks

1. Introduction to Custom Hooks

Custom Hooks are JavaScript functions that allow us to reuse stateful logic between React components. They help us organize repeated logic and keep our components clean and readable.

When multiple components need to fetch API data, we can create a custom hook such as useFetch() and reuse it wherever required.

Remember: A custom Hook name must start with use, such as useFetch. Hooks must be called at the top level of React components or other custom Hooks.

2. Why Use Custom Hooks?

  • Reuse API-fetching logic across components.
  • Reduce duplicate code.
  • Keep components simple and readable.
  • Manage loading, data and error states in one place.
  • Make application logic easier to maintain and test.
Custom Hook: useFetch()
↓
Component A

Displays users

Component B

Displays posts

The same fetching logic can be reused with different API URLs.

3. Creating a Custom Fetch Hook

First, create a file named useFetch.js inside the src/hooks folder. This Hook will manage the API response, loading status and errors.

src/hooks/useFetch.js
import { useEffect, useState } from "react";

function useFetch(url) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

    useEffect(() => {
        const controller = new AbortController();

        async function fetchData() {
            try {
                setLoading(true);
                setError("");
                setData(null);

                const response = await fetch(url, {
                    signal: controller.signal
                });

                if (!response.ok) {
                    throw new Error(
                        `Request failed: ${response.status}`
                    );
                }

                const result = await response.json();
                setData(result);
            } catch (err) {
                if (err.name !== "AbortError") {
                    setError(
                        err instanceof Error
                            ? err.message
                            : "Something went wrong."
                    );
                }
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }

        fetchData();

        return () => {
            controller.abort();
        };
    }, [url]);

    return { data, loading, error };
}

export default useFetch;
How it works: The Hook fetches data whenever the URL changes. It also cancels the previous request during cleanup, helping prevent outdated requests from updating state.

4. Understanding the Custom Hook

Code Purpose
useState() Stores API data, loading status and errors.
useEffect() Starts the request when the URL changes.
fetch(url) Sends the HTTP request to the API.
response.ok Checks whether the HTTP response indicates success.
AbortController Allows the request to be cancelled during cleanup.
return { data, loading, error } Makes the Hook's state available to its component.

5. Using the Custom Hook in a Component

Now create a component named Users.jsx. Import useFetch and pass the users API URL. The component can then display loading, error or data states.

src/components/Users.jsx
import useFetch from "../hooks/useFetch";

function Users() {
    const {
        data: users,
        loading,
        error
    } = useFetch(
        "https://jsonplaceholder.typicode.com/users"
    );

    if (loading) {
        return <p>Loading users...</p>;
    }

    if (error) {
        return (
            <p role="alert">
                Unable to load users: {error}
            </p>
        );
    }

    if (!Array.isArray(users) || users.length === 0) {
        return <p>No users found.</p>;
    }

    return (
        <div>
            <h2>User List</h2>

            <ul>
                {users.map((user) => (
                    <li key={user.id}>
                        <strong>{user.name}</strong>
                        {" - "}
                        {user.email}
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default Users;

6. Reusing the Same Hook for Posts

We do not need to write the same fetching logic again. We can reuse useFetch() with a different URL to retrieve posts.

src/components/Posts.jsx
import useFetch from "../hooks/useFetch";

function Posts() {
    const {
        data: posts,
        loading,
        error
    } = useFetch(
        "https://jsonplaceholder.typicode.com/posts"
    );

    if (loading) {
        return <p>Loading posts...</p>;
    }

    if (error) {
        return (
            <p role="alert">
                Unable to load posts: {error}
            </p>
        );
    }

    if (!Array.isArray(posts) || posts.length === 0) {
        return <p>No posts found.</p>;
    }

    return (
        <div>
            <h2>Posts</h2>

            {posts.slice(0, 5).map((post) => (
                <article key={post.id}>
                    <h3>{post.title}</h3>
                    <p>{post.body}</p>
                </article>
            ))}
        </div>
    );
}

export default Posts;
Important: Each component calling useFetch() gets its own Hook state. The fetching logic is reused, but the state is not automatically shared between components.

7. Displaying Components in App.jsx

Import both components into App.jsx to display the users and posts on the same page.

src/App.jsx
import Users from "./components/Users";
import Posts from "./components/Posts";

function App() {
    return (
        <main>
            <h1>React API Integration</h1>

            <section>
                <Users />
            </section>

            <hr />

            <section>
                <Posts />
            </section>
        </main>
    );
}

export default App;

8. Expected Output

React API Integration

User List

Leanne Graham - Sincere@example.com

Ervin Howell - Shanna@example.com

...more users


Posts

sunt aut facere repellat provident occaecati...

quia et suscipit suscipit recusandae consequuntur expedita...

...more posts

The displayed values come from the testing API. Actual data appears when the application runs and the requests succeed.

9. Best Practices

  • Start custom Hook names with use.
  • Keep the Hook focused on reusable logic.
  • Include reactive dependencies such as the API URL in the dependency array.
  • Handle loading, errors and empty data states.
  • Cancel obsolete requests when appropriate.
  • Do not call Hooks conditionally or inside loops.
  • Use separate Hooks or a data-fetching library when more advanced caching and request coordination are required.

10. Practice Tasks

  1. Create a custom Hook named useFetch.js.
  2. Fetch users and display their names and email addresses.
  3. Reuse the same Hook to fetch posts.
  4. Display loading and error messages.
  5. Test the error state using an invalid API URL.
  6. Modify the URL and observe how the Hook fetches new data.
  7. Add a third component that fetches comments using the same Hook.

Summary

Custom Hooks allow React developers to reuse API-fetching logic across multiple components. By creating a useFetch Hook with useState, useEffect, loading states, error handling and request cleanup, we can build cleaner, reusable and maintainable React applications.