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

Displaying API Data in React

In this lesson, you will learn how to retrieve API data, store it in React state, display records using JSX, render lists with map(), and use unique keys for list items. You will also understand how to handle empty data and structure API results into readable user interfaces.

1. What Does Displaying API Data Mean?

When a React application requests data from an API, the server typically returns information in a format such as JSON. The application can store that information in state and use JSX to display it on the page.

For example, a training institute website may request course details from an API and display the course name, duration, and description in separate cards.

Basic Process

Request Data from API
↓
Parse the JSON Response
↓
Store Data Using useState
↓
Render Data Using JSX
Remember: Fetch retrieves data, state stores the data needed by the component, and JSX describes how that data should appear in the user interface.

2. Understanding the API Response

Before displaying API data, understand the structure of the response. An API may return an array of objects, with each object representing one record.

Example Users Data
[
    {
        "id": 1,
        "name": "Samadhan",
        "email": "samadhan@example.com"
    },
    {
        "id": 2,
        "name": "Samiksha",
        "email": "samiksha@example.com"
    },
    {
        "id": 3,
        "name": "Rahul",
        "email": "rahul@example.com"
    }
]

Here, the response is an array containing three objects. Every object has an id, a name, and an email property.

  • data[0].name accesses the first user's name.
  • data[1].email accesses the second user's email.
  • data.length returns the number of records in the array.
The values above are illustrative. An actual API may return different names, IDs, properties, or numbers of records.

3. Store API Data Using useState

React's useState Hook lets a component store values that may change over time. When API data arrives, the state setter updates the state and React renders the component again.

useState Example
import { useState } from "react";

function Users() {
    const [users, setUsers] = useState([]);

    return (
        <div>
            <h2>Users List</h2>
            <p>Total users: {users.length}</p>
        </div>
    );
}

export default Users;

Explanation

  • useState([]) initializes the state with an empty array.
  • users contains the current array of users.
  • setUsers updates the state.
  • users.length provides the current number of users.
Do not modify the existing state array directly. Use the state setter to update it so React can respond to the change.

4. Fetch API Data and Display It

The following example retrieves users from JSONPlaceholder and displays their names and email addresses. The request runs in useEffect, while the returned records are stored in state.

Users.jsx
import { useEffect, useState } from "react";

function Users() {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        async function fetchUsers() {
            try {
                const response = await fetch(
                    "https://jsonplaceholder.typicode.com/users"
                );

                if (!response.ok) {
                    throw new Error("Failed to fetch users");
                }

                const data = await response.json();

                setUsers(data);
            } catch (error) {
                console.error("Error fetching users:", error);
            }
        }

        fetchUsers();
    }, []);

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

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

export default Users;

How the Code Works

  1. The component starts with an empty users array.
  2. The Effect starts the API request after the component mounts.
  3. The response is checked using response.ok.
  4. The JSON response body is parsed into JavaScript data.
  5. setUsers(data) stores the returned records in state.
  6. React renders the list using the updated state.
This basic example logs request errors to the console. A later lesson will show how to display loading and error messages directly in the user interface.

5. Display Multiple Records Using map()

The map() array method creates a new array by applying a function to each item in the original array. In React, it is commonly used to render a list of components or JSX elements.

Using map()
const courses = [
    { id: 1, name: "React" },
    { id: 2, name: "Angular" },
    { id: 3, name: "Node.js" }
];

function CourseList() {
    return (
        <ul>
            {courses.map(course => (
                <li key={course.id}>
                    {course.name}
                </li>
            ))}
        </ul>
    );
}

export default CourseList;

Expected Output

Course List

  • React
  • Angular
  • Node.js

The example uses local sample data to demonstrate rendering. The same pattern works when the array comes from an API.

6. Why Is the key Prop Important?

When React renders a list, each sibling element should have a stable and unique key. The key helps React identify which items have changed, been added, or been removed.

Correct Key Usage
{users.map(user => (
    <li key={user.id}>
        {user.name}
    </li>
))}

Important Points

  • Use a unique, stable identifier such as the record ID.
  • Keys should be unique among siblings in the rendered list.
  • Avoid generating a new random key on every render.
  • Array indexes are usually not ideal when items can be reordered, inserted, or deleted.
The key is used by React during reconciliation. It is not automatically passed to the child component as a normal prop.

7. Display API Data in Cards

Lists are useful for simple records. Cards are another way to organize information when each record contains multiple fields. For example, a course card can show the course name, duration, and description.

CourseCards.jsx
const courses = [
    {
        id: 1,
        name: "React",
        duration: "6 Weeks",
        description: "Learn React components and Hooks."
    },
    {
        id: 2,
        name: "Node.js",
        duration: "8 Weeks",
        description: "Learn server-side JavaScript."
    }
];

function CourseCards() {
    return (
        <div>
            <h2>Available Courses</h2>

            {courses.map(course => (
                <article key={course.id}>
                    <h3>{course.name}</h3>
                    <p>Duration: {course.duration}</p>
                    <p>{course.description}</p>
                </article>
            ))}
        </div>
    );
}

export default CourseCards;

This example uses local data to demonstrate the layout. In a real application, you can replace the local array with API data stored in React state.

8. Handle Empty API Data

An API may return an empty array when no records are available. Rather than showing a blank list, the application can display a helpful message.

Conditional Rendering
{users.length === 0 ? (
    <p>No users available.</p>
) : (
    <ul>
        {users.map(user => (
            <li key={user.id}>
                {user.name}
            </li>
        ))}
    </ul>
)}
An empty array can mean that the request succeeded but there are no records. It does not necessarily mean the API request failed. In a complete application, distinguish an empty result from the initial loading state and an error state.

9. Common Mistakes

  • Not parsing the response: Use response.json() when the API returns JSON.
  • Rendering before data arrives: Initialize state with a suitable value such as an empty array.
  • Forgetting list keys: Add a stable key to each mapped list item.
  • Accessing missing properties: Confirm that the API response contains the property names your JSX uses.
  • Ignoring HTTP errors: Check response.ok before using the response body.
  • Updating state directly: Use a state setter instead of modifying the current array in place.

10. Practice Tasks

Task 1: Display User Names

Fetch users from https://jsonplaceholder.typicode.com/users and display their names in an unordered list.

Task 2: Display User Details

Display each user's name, email, and username using separate JSX elements.

Task 3: Create Course Cards

Create course objects containing an ID, name, duration, and description. Display each course using a card-style layout.

Task 4: Show an Empty Message

Display "No records available" when the array is empty and render the list when records exist.

Task 5: Understand Keys

Render an API array using map() and assign a stable unique key to each list item.

Summary

In this lesson, you learned how to display API data in React, understand JSON arrays and objects, store records with useState, retrieve information using Fetch and useEffect, and render lists with map(). You also learned why stable keys are important, how to display records in cards, and how to handle empty data. In the next lesson, you will learn how to manage loading and error states so users receive clear feedback while API requests are in progress or fail.