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

1. Introduction to Controlled Components

A controlled component is a form element whose value is controlled by React state. The input receives its value through a value prop, and an event handler updates the state when the user changes the input.

Because React state stores the current value, the component can read, display, validate, and update the information entered by the user.

Remember: A controlled input usually uses both value and onChange.

2. How Controlled Components Work

React stores the input value in state. When the user types, the onChange handler updates that state, and React renders the input with the latest value.

React State Stores the current input value
↓
Input Value value={name}
↓
User Types onChange handler runs
↓
State Updates React displays the new value
Important: The onChange handler must update the state used by the input's value prop. Otherwise, the input will not respond normally to user typing.

3. Creating a Controlled Text Input

We can use the useState hook to store a text input's value. The onChange handler reads the latest value from the event object and updates the state.

Example

import { useState } from "react";

function NameInput() {
    const [name, setName] = useState("");

    function handleChange(event) {
        setName(event.target.value);
    }

    return (
        <div>
            <label htmlFor="studentName">
                Student Name:
            </label>

            <input
                id="studentName"
                type="text"
                value={name}
                onChange={handleChange}
            />

            <p>Name: {name}</p>
        </div>
    );
}

export default NameInput;

Expected Output

Name: Rahul

The value of the input comes from the name state. When the user types, handleChange updates the state and React displays the new name.

4. Using an Inline onChange Handler

Instead of defining a separate function, we can write an arrow function directly inside the onChange prop. This is useful for simple input updates.

Example

import { useState } from "react";

function EmailInput() {
    const [email, setEmail] = useState("");

    return (
        <div>
            <label htmlFor="email">Email:</label>

            <input
                id="email"
                type="email"
                value={email}
                onChange={(event) =>
                    setEmail(event.target.value)
                }
            />

            <p>Email: {email}</p>
        </div>
    );
}

export default EmailInput;

Expected Output

Email: student@example.com

The inline arrow function reads event.target.value and passes the entered email to setEmail.

5. Handling Multiple Controlled Inputs

A form can contain multiple controlled inputs. We can store their values in one state object and use each input's name attribute to identify which value to update.

Example

import { useState } from "react";

function RegistrationForm() {
    const [formData, setFormData] = useState({
        name: "",
        email: ""
    });

    function handleChange(event) {
        const { name, value } = event.target;

        setFormData((previousData) => ({
            ...previousData,
            [name]: value
        }));
    }

    return (
        <div>
            <label htmlFor="name">Name:</label>
            <input
                id="name"
                name="name"
                value={formData.name}
                onChange={handleChange}
            />

            <label htmlFor="email">Email:</label>
            <input
                id="email"
                name="email"
                type="email"
                value={formData.email}
                onChange={handleChange}
            />

            <p>Name: {formData.name}</p>
            <p>Email: {formData.email}</p>
        </div>
    );
}

export default RegistrationForm;

Expected Output

Name: Rahul

Email: rahul@example.com

The name property identifies the field being updated. The spread operator keeps the other form values when the state object is updated.

Remember: When updating an object in React state, preserve the existing properties that should remain unchanged.

6. Creating a Controlled Checkbox

For a checkbox, the checked prop represents whether the checkbox is selected. The onChange handler updates the state when the user checks or unchecks it.

Example

import { useState } from "react";

function TermsCheckbox() {
    const [accepted, setAccepted] = useState(false);

    return (
        <div>
            <label>
                <input
                    type="checkbox"
                    checked={accepted}
                    onChange={(event) =>
                        setAccepted(event.target.checked)
                    }
                />

                I accept the terms and conditions
            </label>

            <p>
                Accepted: {accepted ? "Yes" : "No"}
            </p>
        </div>
    );
}

export default TermsCheckbox;

Expected Output

Accepted: No

A checkbox uses checked rather than value to control whether it is selected. The event's target.checked property provides its current boolean value.

7. Creating a Controlled Select

A select element allows users to choose an option. Its value prop can be connected to state so React controls the selected option.

Example

import { useState } from "react";

function CourseSelect() {
    const [course, setCourse] = useState("React");

    return (
        <div>
            <label htmlFor="course">Choose a Course:</label>

            <select
                id="course"
                value={course}
                onChange={(event) =>
                    setCourse(event.target.value)
                }
            >
                <option value="React">React</option>
                <option value="Angular">Angular</option>
                <option value="Python">Python</option>
            </select>

            <p>Selected Course: {course}</p>
        </div>
    );
}

export default CourseSelect;

Expected Output

Selected Course: React

The selected course is stored in state. When the user chooses a different option, the onChange handler updates the course value.

8. Common Mistakes

Mistake 1: Missing the onChange Handler

<input value={name} />

A text input with a value prop but no state-updating handler is read-only from the user's perspective.

Correct Code

<input
    value={name}
    onChange={(event) =>
        setName(event.target.value)
    }
/>

Mistake 2: Using value for Checkbox Selection

<input
    type="checkbox"
    value={accepted}
/>

The value prop does not control whether a checkbox is selected. Use the checked prop instead.

Correct Code

<input
    type="checkbox"
    checked={accepted}
    onChange={(event) =>
        setAccepted(event.target.checked)
    }
/>

Mistake 3: Losing Other State Properties

setFormData({
    [name]: value
});

This replaces the state object and removes properties that were not included in the new object.

Correct Code

setFormData((previousData) => ({
    ...previousData,
    [name]: value
}));

9. Practice Tasks

Complete these tasks to practise controlled components.

Task 1: Create a controlled text input that displays the entered student name below the field.
Task 2: Create controlled name and email fields using one state object.
Task 3: Create a controlled checkbox and display Yes or No depending on its checked state.
Task 4: Create a controlled select element with three course options.
Task 5: Create a registration form that preserves all existing field values when one input changes.

Summary

Controlled components are form elements whose values are managed by React state. Text inputs and select elements commonly use value with onChange, while checkboxes use checked with onChange. State can store one input value or an object containing multiple form values. Updating state through event handlers keeps the displayed fields synchronized with React and provides a reliable foundation for form validation and submission.