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

useState Hook

Learn how to use the useState Hook to store, manage, and update data in React functional components.

1. What Is the useState Hook?

The useState Hook is a built-in React Hook that allows functional components to store and update state. State represents information that can change while a component is being used.

For example, a counter value, a student's name, a selected course, or a form input value can be stored using state. When state changes, React updates the component's UI when necessary.

Remember: Import useState from React before using it in your component.

2. Syntax of useState

The basic syntax of the useState Hook is:

const [state, setState] = useState(initialValue);

Here is what each part means:

  • state: The current state value.
  • setState: The function used to update the state value.
  • useState(initialValue): Initializes the state with the given value.
Important: The setter function schedules a state update. When the updated state is rendered, the UI reflects the new value.

3. How useState Works

The state update process follows these steps:

Initial State
→
User Action
→
Update State
→
Re-render UI

React initializes the state when the component is rendered. When an event handler calls the setter function, React schedules an update and renders the component with the updated state.

4. Example: Counter Using useState

In this example, the counter starts at zero. Clicking the button increases the count by one.

Example Code

import { useState } from "react";

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

    function increaseCount() {
        setCount(count + 1);
    }

    return (
        <div>
            <h2>Counter Application</h2>

            <p>Count: {count}</p>

            <button onClick={increaseCount}>
                Increase
            </button>
        </div>
    );
}

export default App;

Expected Output

Counter Application

Initial value: Count: 0

After clicking Increase once: Count: 1

After clicking Increase again: Count: 2

Explanation: The useState(0) statement initializes the counter to zero. The setCount() function updates the counter, and React renders the new value.

5. Example: Updating a String State

The useState Hook can also store text values, such as a student's name.

Example Code

import { useState } from "react";

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

    function changeName() {
        setName("Samiksha");
    }

    return (
        <div>
            <h2>Student Name</h2>

            <p>Name: {name}</p>

            <button onClick={changeName}>
                Change Name
            </button>
        </div>
    );
}

export default App;

Expected Output

Before clicking the button:

Name: Samadhan

After clicking Change Name:

Name: Samiksha
Explanation: The initial state is set to "Samadhan". When the button is clicked, setName("Samiksha") updates the state and React displays the updated name.

6. Using Multiple State Variables

A component can use the useState Hook multiple times to manage different values independently.

Example Code

import { useState } from "react";

function App() {
    const [name, setName] = useState("Samadhan");
    const [course, setCourse] = useState("React");

    return (
        <div>
            <h2>Student Information</h2>

            <p>Name: {name}</p>
            <p>Course: {course}</p>

            <button onClick={() => setName("Samiksha")}>
                Change Name
            </button>

            <button onClick={() => setCourse("Angular")}>
                Change Course
            </button>
        </div>
    );
}

export default App;

Expected Output

Initially:

Name: Samadhan
Course: React

After clicking Change Name:

Name: Samiksha

After clicking Change Course:

Course: Angular
Explanation: The component uses two independent state variables: name and course. Each setter updates its corresponding state value.

7. Important Points About useState

  • Import useState from React before using it.
  • Call useState at the top level of a functional component or custom Hook.
  • Do not call Hooks inside loops, conditions, or nested functions.
  • Use the setter function to update state instead of directly modifying the state variable.
  • State can store strings, numbers, booleans, arrays, objects, and other JavaScript values.
  • State updates may be batched, so the updated value should not be expected immediately in the same executing line.
Tip: When the next state depends on the previous state, you can use a functional update, such as setCount(previousCount => previousCount + 1).

8. Practice Tasks

Complete these exercises to practise the useState Hook:

  1. Create a counter that starts at 0 and increases by 1 when a button is clicked.
  2. Create a counter with Increase and Decrease buttons.
  3. Store a student's name in state and change it when a button is clicked.
  4. Create a component that switches a message between "Hello" and "Welcome".
  5. Store a course name and student name using separate state variables.
  6. Create a button that toggles a boolean state between true and false.

Summary

The useState Hook allows React functional components to store and update changing data. It returns the current state value and a setter function that schedules updates and allows React to render the updated UI. State can hold different types of values, including strings, numbers, booleans, arrays, and objects. By using useState correctly and following the Rules of Hooks, developers can create interactive counters, forms, student information displays, and other dynamic React applications at CIIT Training Institute.