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

Environment Variables for API URLs

1. Introduction to Environment Variables

Environment variables allow us to configure application settings without hardcoding them throughout our React components. For example, an application may use one API URL during development and a different API URL in production.

Instead of repeating the API URL in every component, we can store the base URL in an environment variable and reuse it wherever API requests are required.

Important: This lesson uses Vite, a common tool for creating React applications. In Vite, frontend environment variables that must be exposed to client-side code use the VITE_ prefix.

2. Why Use Environment Variables?

  • Avoid repeating API URLs in multiple files.
  • Switch API endpoints between development and production.
  • Make application configuration easier to maintain.
  • Keep environment-specific settings outside component logic.
  • Reduce code changes when the API server address changes.
.env Configuration
↓
import.meta.env
↓
API Service / React Component
↓
Backend API

3. Creating an Environment Variable

In a Vite React project, create a file named .env in the project root, where package.json is located.

.env
VITE_API_BASE_URL=https://jsonplaceholder.typicode.com

This variable stores the base URL of the API. We can now use it in our React application instead of hardcoding the complete URL in every request.

Remember: Environment variable names must use the VITE_ prefix to be exposed through import.meta.env in a Vite application.

4. Accessing Environment Variables

Vite provides environment variables through import.meta.env. We can read our configured API URL using the following code.

Access API URL
const API_BASE_URL =
    import.meta.env.VITE_API_BASE_URL;

console.log(API_BASE_URL);

Expected output:

https://jsonplaceholder.typicode.com
Note: After creating or changing an .env file, restart the Vite development server so the updated configuration is loaded.

5. Using Environment Variables in API Requests

We can combine the base URL with an API endpoint to fetch data. This makes it easier to update the API server address in one place.

src/services/api.js
const API_BASE_URL =
    import.meta.env.VITE_API_BASE_URL;

export async function getUsers() {
    if (!API_BASE_URL) {
        throw new Error(
            "API base URL is not configured."
        );
    }

    const response = await fetch(
        `${API_BASE_URL}/users`
    );

    if (!response.ok) {
        throw new Error(
            `Failed to fetch users: ${response.status}`
        );
    }

    return response.json();
}

Here, getUsers() uses the configured base URL and adds the /users endpoint to create the complete request URL.

6. Displaying API Data in a React Component

Now we can import the API service into a component and display the users with loading and error states.

src/components/Users.jsx
import { useEffect, useState } from "react";
import { getUsers } from "../services/api";

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

    useEffect(() => {
        async function loadUsers() {
            try {
                const data = await getUsers();
                setUsers(data);
            } catch (err) {
                setError(
                    err instanceof Error
                        ? err.message
                        : "Unable to load users."
                );
            } finally {
                setLoading(false);
            }
        }

        loadUsers();
    }, []);

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

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

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

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

export default Users;

7. Different Environment Files

Vite supports different environment files for different environments. For example, you can configure separate API URLs for development and production.

.env.development
VITE_API_BASE_URL=http://localhost:5000/api
.env.production
VITE_API_BASE_URL=https://api.example.com

Vite loads the appropriate environment-specific configuration according to the selected mode. Replace these example URLs with the actual endpoints used by your application.

8. Environment Variables: Best Practices

  • Use meaningful names such as VITE_API_BASE_URL.
  • Keep environment files in the project root.
  • Use different configuration values for development and production.
  • Add local secret-containing environment files to .gitignore when appropriate.
  • Provide an example configuration file for other developers.
  • Restart the development server after changing environment variables.
  • Validate required configuration before sending API requests.
Security warning: Any variable exposed to frontend code can be seen by users in the browser bundle. Never store passwords, private API keys, database credentials or other secrets in VITE_ variables. Keep secrets on the backend.

9. Common Problems and Solutions

Problem Possible Solution
Variable is undefined Check the VITE_ prefix and variable name.
Old API URL is still used Restart the Vite development server.
API request fails Check the URL, server status, CORS configuration and network connection.
Secret appears in frontend code Remove it from client-side configuration and move it to the backend.
Production uses the wrong URL Verify the production environment configuration and build mode.

10. Practice Tasks

  1. Create a Vite React project and add a .env file.
  2. Configure VITE_API_BASE_URL.
  3. Read the variable using import.meta.env.
  4. Create an API service file and fetch users.
  5. Display the API response in a React component.
  6. Create development and production environment configurations.
  7. Test what happens when the API URL is missing or incorrect.

Summary

Environment variables help React applications manage configuration such as API base URLs across development and production environments. In Vite, variables prefixed with VITE_ can be accessed through import.meta.env. Keeping API configuration separate from component logic improves maintainability, while sensitive credentials must remain on the backend.