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

Using Axios in React

1. Introduction to Axios

Axios is a JavaScript library used to make HTTP requests from React applications to external APIs and backend servers. It supports GET, POST, PUT, PATCH and DELETE requests.

Axios automatically converts JSON response data into JavaScript objects. It also provides convenient error handling and request configuration options.

Remember: Axios is an external library, so you must install it before importing it into your React project.

2. Installing Axios

Open your React project's terminal and execute the following command:

Terminal
npm install axios

After installation, import Axios into your component:

Import Axios
import axios from "axios";

3. Fetching Data Using Axios GET

The axios.get() method sends a GET request to retrieve information from an API. The response data is available through response.data.

Basic GET Request
import axios from "axios";

async function getUsers() {
    try {
        const response = await axios.get(
            "https://jsonplaceholder.typicode.com/users"
        );

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

getUsers();
Important: Unlike Fetch, Axios normally rejects the request promise for HTTP status codes outside the configured successful status range. Network errors are also handled through the catch block.

4. Displaying API Data in React

We can combine Axios with React's useState and useEffect hooks to fetch and display data when a component loads.

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

function AxiosUsers() {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

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

                setUsers(response.data);
            } catch (err) {
                setError("Unable to load users. Please try again.");
            } finally {
                setLoading(false);
            }
        }

        fetchUsers();
    }, []);

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

    if (error) {
        return <p role="alert">{error}</p>;
    }

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

            {users.length === 0 ? (
                <p>No users found.</p>
            ) : (
                <ul>
                    {users.map((user) => (
                        <li key={user.id}>
                            <strong>{user.name}</strong>
                            {" - "}
                            {user.email}
                        </li>
                    ))}
                </ul>
            )}
        </div>
    );
}

export default AxiosUsers;

5. Sending POST Requests Using Axios

The axios.post() method sends data to a server. The first argument is the API URL, and the second argument contains the data to send.

POST Request Example
import axios from "axios";

async function createUser() {
    const newUser = {
        name: "Samadhan",
        email: "samadhan@example.com"
    };

    try {
        const response = await axios.post(
            "https://jsonplaceholder.typicode.com/users",
            newUser
        );

        console.log("Created user:", response.data);
    } catch (error) {
        console.error("Error creating user:", error.message);
    }
}

createUser();
Note: JSONPlaceholder is a testing API. Its POST endpoint simulates creating a resource; it does not permanently save the new user.

6. Axios Error Handling

Axios errors can be handled in a catch block. We can check whether the server returned an error response, the request received no response, or the request could not be configured or sent.

Handling Different Errors
import axios from "axios";

async function fetchData() {
    try {
        const response = await axios.get(
            "https://jsonplaceholder.typicode.com/users"
        );

        console.log(response.data);
    } catch (error) {
        if (axios.isAxiosError(error)) {
            if (error.response) {
                console.error(
                    "Server error:",
                    error.response.status
                );
            } else if (error.request) {
                console.error(
                    "No response received from the server."
                );
            } else {
                console.error(
                    "Request error:",
                    error.message
                );
            }
        } else {
            console.error("Unexpected error:", error);
        }
    }
}

fetchData();

7. Fetch API vs Axios

Feature Fetch API Axios
Installation Built into modern browsers Requires installation
JSON Response Call response.json() Available in response.data
HTTP Errors Check response.ok Rejects non-success status codes by default
POST Requests Configure method, headers and body Use axios.post(url, data)
Request Interceptors Not built in Supported

8. Axios Request Flow

React Component
↓
Axios GET / POST Request
↓
API Server
↓
Response Data or Error
↓
Update React State and UI

9. Best Practices

  • Keep API request logic organized in reusable functions.
  • Use loading and error states to improve the user experience.
  • Use environment variables for configurable API base URLs.
  • Do not expose secret API keys in frontend environment variables.
  • Use Axios interceptors when shared request or response handling is needed.
  • Cancel or ignore outdated requests when necessary, especially when components unmount or parameters change.

10. Practice Tasks

  1. Install Axios in your React project.
  2. Fetch users using axios.get().
  3. Display user names and email addresses.
  4. Send a POST request with a new user's details.
  5. Display loading and error messages.
  6. Compare the same GET request using Fetch and Axios.

Summary

Axios simplifies API integration in React by providing convenient methods for HTTP requests, automatic JSON response transformation and promise-based error handling. By combining Axios with React hooks, loading states and error handling, we can build reliable applications that communicate effectively with backend APIs.