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 in React

Learn how to declare state in functional components using the useState Hook. Understand initial values, state variables, setter functions, and practical examples for interactive React applications.

1. What Is the useState Hook?

The useState Hook is a built-in React Hook that allows a function component to store and update state.

It returns two values: the current state value and a setter function that requests an update to that value.

For example, a CIIT Training Institute student dashboard can use state to store the number of completed courses, the selected course, or the text entered into a form.

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

const [count, setCount] = useState(0);
In simple words: useState lets a component remember a value and request an update when that value needs to change.

2. Syntax of useState

The general syntax of the useState Hook is:

Syntax
const [state, setState] = useState(initialValue);
Part Meaning
useState The React Hook used to declare state.
state The current state value for the current render.
setState The function used to request a state update.
initialValue The initial state value used when the component initializes.

The names state and setState are examples. You can choose meaningful names such as count and setCount, or name and setName.

3. Importing useState

Before using the Hook, import it from React. You can then call it at the top level of your function component.

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

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

    return (
        <h2>Count: {count}</h2>
    );
}

export default Counter;

Explanation:

  • import { useState } from "react" imports the Hook.
  • useState(0) initializes the count to 0.
  • count holds the current count value.
  • setCount requests a count update.

Expected Browser Output

Count: 0

4. How useState Works

When React renders a component, it provides the current state value. When the setter is called, React schedules an update and renders the component again when necessary.

Step-by-step:

  1. React renders the component.
  2. The component reads its current state value.
  3. A user performs an action, such as clicking a button.
  4. The setter requests a new state value.
  5. React renders the component with the updated value.
Important: Calling a setter does not change the state variable in the already-running render. The updated value is available on a subsequent render.

5. Example: Counter with useState

A counter is one of the easiest ways to understand useState. The initial count is 0. Every button click requests an increment of the count.

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

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

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

    return (
        <div>
            <h2>Counter: {count}</h2>

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

export default Counter;

How the code works:

  • The counter starts at 0.
  • The Increase button calls increaseCount.
  • increaseCount requests the next count value.
  • React renders the new count in the heading.

Expected Browser Output

Initially: Counter: 0

After one click: Counter: 1

After two clicks: Counter: 2

6. Different Initial Values

The useState Hook can store different JavaScript data types. The initial value determines the starting value for that state variable.

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

function StudentInfo() {
    const [name, setName] = useState("Rahul");
    const [age, setAge] = useState(20);
    const [isActive, setIsActive] = useState(true);

    return (
        <div>
            <p>Name: {name}</p>
            <p>Age: {age}</p>
            <p>Active: {isActive ? "Yes" : "No"}</p>
        </div>
    );
}

export default StudentInfo;
State Variable Initial Value Type
name "Rahul" String
age 20 Number
isActive true Boolean

Expected Browser Output

Name: Rahul

Age: 20

Active: Yes

7. Updating State with a Setter

A setter can receive the next state value directly. For example, setName("Amit") requests that the name state be updated to Amit.

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

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

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

    return (
        <div>
            <p>Student Name: {name}</p>

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

export default Student;

Expected Browser Output

Before clicking: Student Name: Rahul

After clicking: Student Name: Amit

Remember: The setter requests the update. React displays the new value when the component renders with that state.

8. Rules of the useState Hook

  • Call useState at the top level of a function component or custom Hook.
  • Do not call Hooks inside conditions, loops, or nested functions.
  • Use the setter function instead of directly assigning a new value to state.
  • Treat objects and arrays in state as immutable.
  • Use a functional update when the next value depends on the previous value.
FunctionalUpdate.jsx
import { useState } from "react";

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

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

    return (
        <button onClick={increaseCount}>
            Count: {count}
        </button>
    );
}

export default Counter;

The functional updater receives the previous state value and calculates the next value from it. This is useful when an update depends on the previous state.

9. Common Mistakes

Mistake 1: Forgetting to import useState

If you use the named Hook without importing it, your component may fail to compile or run.

Mistake 2: Changing state directly

Incorrect and Correct
// Incorrect
count = count + 1;

// Correct
setCount(count + 1);

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

Mistake 3: Calling useState conditionally

Incorrect
if (isLoggedIn) {
    const [count, setCount] = useState(0);
}

Call useState at the top level of the component instead so that Hook calls remain in the same order between renders.

10. Quick Practice

Try these exercises in your React project:

  1. Create a counter using useState.
  2. Change a student's name when a button is clicked.
  3. Store an age as a number in state.
  4. Use a Boolean state value to show or hide a message.
  5. Explain the difference between a state value and its setter.
Practice Tip: The code on this Razor page is for learning. Run the examples inside a React application to test the actual button interactions and state updates.

Summary

The useState Hook lets function components store and update state. It returns the current state value and a setter function. The initial value is used when the component initializes, while setter calls request updates that React can render on the screen. useState can manage numbers, strings, Boolean values, and other JavaScript data. Following the Rules of Hooks and updating state correctly helps build reliable interactive applications.