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

Introduction to State in React

State is a fundamental React concept that allows components to remember information, respond to user interactions, and display updated data. In this lesson, we will understand state through diagrams, examples, and practical applications.

1. What Is State in React?

State is data that a React component manages over time. Its value may change when a user clicks a button, enters information, selects an option, or performs another action.

When state is updated through its setter function, React schedules a render so that the component can display the latest state value.

  • State stores changing information.
  • State belongs to a component instance.
  • State updates can cause the UI to render again.
  • State is useful for forms, counters, menus and dashboards.
Example.jsx
import { useState } from "react";

function Counter() {
    const [count, setCount] = useState(0);

    return (
        <div>
            <h2>Count: {count}</h2>
            <button onClick={() => setCount(count + 1)}>
                Increase
            </button>
        </div>
    );
}

export default Counter;

Expected Browser Output

Initially: Count: 0

After one click: Count: 1

After two clicks: Count: 2

2. Why Do We Need State?

Normal JavaScript variables alone do not tell React that the UI needs to be updated. State gives React a way to preserve a value between renders and respond to changes.

Application Example State
Counter Current count
Student registration Name and form field values
Navigation menu Whether the menu is open
Course dashboard Selected course or filter
Shopping cart Selected cart items
Remember: Use state when a changing value must be preserved between renders and reflected in the React user interface.

3. State Update Flow Diagram

This diagram explains how a user action updates state and how React displays the new value.

Step-by-step explanation:

  1. The user clicks the Increase button.
  2. The onClick event handler executes.
  3. The setter requests a state update.
  4. React renders the component with the updated state.
  5. The displayed count changes from 0 to 1.

4. Understanding the useState Hook

The useState Hook allows a functional component to declare state. It provides the current state value and a function used to request updates to that value.

useState Syntax
const [count, setCount] = useState(0);
Part Explanation
useState The React Hook used to declare state.
count The current state value for this render.
setCount The function used to request a state update.
0 The initial state value for the first render.
Important: Import useState from React and call it at the top level of your component, not inside a condition or loop.

5. Practical Example: Course Status

Imagine a CIIT student dashboard. A course initially shows In Progress. When the student clicks Complete Course, the status changes to Completed.

CourseStatus.jsx
import { useState } from "react";

function CourseStatus() {
    const [status, setStatus] = useState("In Progress");

    function completeCourse() {
        setStatus("Completed");
    }

    return (
        <div>
            <h2>React Fundamentals</h2>
            <p>Status: {status}</p>

            <button onClick={completeCourse}>
                Complete Course
            </button>
        </div>
    );
}

export default CourseStatus;

Expected Browser Output

Course: React Fundamentals

Initial Status: In Progress

After clicking the button: Completed

Here, status stores the current value and setStatus requests the update. React then renders the component with the new status.

6. State vs Normal Variables

A normal local variable does not itself trigger a React render. React state is preserved between renders, and updating state through its setter can schedule a new render.

Normal Variable React State
Does not itself trigger a React render. Setter updates can schedule a render.
Local value is recreated when the function runs again. React preserves state between renders.
Useful for temporary calculations. Useful for values that affect the UI.

7. Important Rules of State

  • Use a state setter to update state.
  • Do not mutate state objects or arrays directly.
  • Call Hooks at the top level of functional components.
  • React may batch state updates.
  • Use a functional update when the next value depends on the previous value.
Functional Update Example
import { useState } from "react";

function Counter() {
    const [count, setCount] = useState(0);

    function increase() {
        setCount(previousCount => previousCount + 1);
    }

    return (
        <button onClick={increase}>
            Count: {count} - Increase
        </button>
    );
}

export default Counter;

Expected Browser Output

Initially: Count: 0

After clicking: Count: 1

8. Common Mistakes

  • Assigning a new value directly to a state variable.
  • Forgetting to import useState.
  • Calling a Hook inside an if statement or loop.
  • Expecting the current state variable to change immediately in the same handler.
  • Using state for a value that can simply be calculated during rendering.
Incorrect vs Correct
// Incorrect
count = count + 1;

// Correct
setCount(count + 1);

// When based on the previous value
setCount(previousCount => previousCount + 1);

9. Quick Practice

Try these exercises in your React project:

  1. Create a counter with Increase and Decrease buttons.
  2. Create a toggle button to show or hide a message.
  3. Build a student form with a state variable for the name.
  4. Change a course status from Learning to Completed.
  5. Explain how the state setter causes the UI to update.
Practice Tip: Run these examples inside your React application. The code blocks on this Razor page are educational examples; they do not execute as React components inside this page.

10. Quick Revision

  • State stores changing information in a component.
  • useState is a Hook for declaring state.
  • The setter requests a state update.
  • React renders the component using the latest state.
  • State is essential for interactive React applications.

Summary

State is a core React concept that lets components preserve changing data between renders. The useState Hook provides the current value and a setter function. When the setter requests an update, React can render the component with the latest value and update the UI. State is useful for counters, forms, menus, course progress and other interactive features. Understanding state prepares you for the next lessons on useState, updating state, functional updates, objects, arrays, immutability and lifting state up.