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

What Is State in React?

Learn how React state stores changing information, remembers values between renders, and updates the user interface when users interact with an application.

1. What Is State?

State is information that a React component remembers between renders. It can represent a counter value, a student's name, a selected course, or whether a menu is open or closed.

When a user performs an action, a component can request a state update. React then renders the component again when necessary to display the updated information.

Simple example:

Imagine a CIIT Training Institute student dashboard. The dashboard displays the number of courses completed by a student. When a course is completed, that number can change from 2 to 3.

Remember: State is useful when a component needs to remember changing information and display it in the user interface.

2. Why Do We Need State?

Websites often need to respond to user interactions. For example, a counter must display a new number after a button click, and a form must remember the text entered by a student.

A normal local variable does not itself tell React to render the component again. React state provides a way to preserve information between renders and request UI updates when the value changes.

Application Feature State Example
Counter Current number
Student registration Entered name and form values
Course dashboard Selected course or progress
Navigation menu Open or closed status
Search interface Current search text

3. Understanding State with an Example

Let's create a simple counter. Its initial value is 0. Every time the user clicks the Increase button, React updates the state and displays the new count.

Counter.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;

Code explanation:

  • useState(0) declares state with an initial value of 0.
  • count represents the current state value for that render.
  • setCount requests an update to the count.
  • onClick calls the setter when the button is clicked.
  • {count} displays the current count in JSX.

Expected Browser Output

Initial display: Count: 0

After one click: Count: 1

After two clicks: Count: 2

4. How State Updates the UI

State connects user interactions with the information displayed by a React component. The following diagram shows the basic flow.

Step-by-step explanation:

  1. The user clicks the Increase button.
  2. The button's event handler runs.
  3. The state setter requests a new count value.
  4. React renders the component with the new state.
  5. The screen displays the updated count.
Important: Calling a state setter requests an update. The current state variable does not change immediately inside the already-running event handler.

5. State and Normal Variables

JavaScript variables and React state serve different purposes. A normal local variable is recreated when the component function runs again. Changing that variable does not itself trigger a React render.

NormalVariable.jsx
function Example() {
    let count = 0;

    function increase() {
        count = count + 1;
        console.log(count);
    }

    return (
        <button onClick={increase}>
            Increase
        </button>
    );
}

export default Example;

In this example, the variable changes when the handler runs, but that change does not itself make React render the new value on the screen.

Now compare it with React state:

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

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

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

export default Example;
Normal Variable React State
Changing it does not itself trigger a render. Setter updates can schedule a render.
A local variable is recreated when the function runs again. React preserves state between renders.
Useful for temporary calculations. Useful for changing values displayed in the UI.

6. State Can Store Different Types of Data

React state is not limited to numbers. It can store strings, Boolean values, arrays, objects, and other JavaScript values.

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

function StudentDashboard() {
    const [studentName, setStudentName] = useState("Rahul");
    const [isEnrolled, setIsEnrolled] = useState(true);
    const [completedCourses, setCompletedCourses] = useState(2);

    return (
        <div>
            <p>Student: {studentName}</p>
            <p>Enrolled: {isEnrolled ? "Yes" : "No"}</p>
            <p>Completed Courses: {completedCourses}</p>
        </div>
    );
}

export default StudentDashboard;
State Variable Data Type Initial Value
studentName String Rahul
isEnrolled Boolean true
completedCourses Number 2

Expected Browser Output

Student: Rahul

Enrolled: Yes

Completed Courses: 2

7. Important Rules of State

  • Use the state setter to request an update.
  • Do not directly mutate state objects or arrays.
  • Call Hooks at the top level of a function component or custom Hook.
  • State updates may be batched by React.
  • Use functional updates when the next state depends on the previous state.
  • Treat state values as read-only.
Remember: State belongs to a component instance. Two separate instances of the same component can maintain separate state values.

8. Common Mistakes

Mistake 1: Updating a state variable directly

Incorrect
count = count + 1;

Direct assignment does not request a React state update. Use the setter instead.

Correct
setCount(count + 1);

Mistake 2: Expecting an immediate state change

A state setter requests an update. Reading the same state variable immediately afterward in the current handler still gives the value from that render.

Mistake 3: Calling Hooks conditionally

Do not call useState inside an if statement, loop, or nested function. Call it at the top level of your component.

9. Practice Exercises

Try the following exercises in your React project:

  1. Create a counter that starts at 0.
  2. Add Increase and Decrease buttons.
  3. Create a button that shows or hides a message.
  4. Store a student's name in state.
  5. Display the number of completed courses.
  6. Explain why a state setter can update the UI.
Practice Tip: The code samples on this Razor page are learning examples. To execute them, place the React code in your React project.

10. Quick Revision

  • State stores information that a component remembers.
  • State can contain numbers, strings, Boolean values, arrays, and objects.
  • useState is a Hook used to declare state.
  • The setter requests a state update.
  • React can render the component using the updated state.
  • State makes interactive user interfaces possible.

Summary

React state allows components to remember information between renders. It is useful for counters, student forms, course dashboards, menus, and other interactive features. The useState Hook provides the current state value and a setter function. When an update is requested, React can render the component again and display the updated information. In the next lesson, we will learn how to use the useState Hook in detail.