Lesson 29 of 60 – useState Hook
48%

useState Hook

The useState Hook is one of the most commonly used Hooks in React. It allows functional components to store and update data that can change while the application is running.

Note: When a state value is updated using its setter function, React schedules the component to render again with the updated state.

1. What is useState?

useState is a React Hook that allows a functional component to create and manage state.

import { useState } from "react";

function App() {

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

    return (
        <h1>
            {count}
        </h1>
    );

}

2. What is State?

State is data that belongs to a component and can change over time.

Examples of state include:

  • Counter value
  • Username
  • Login status
  • Selected course
  • Form values
  • Menu visibility

3. Importing useState

Before using useState, import it from React.

import { useState } from "react";

This makes the Hook available inside the component.

4. Basic useState Syntax

The basic syntax is:

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

There are three important parts:

  • state — current state value.
  • setState — function used to update the state.
  • initialValue — starting value.

5. Creating a Counter State

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

Here:

  • count contains the current value.
  • setCount updates the value.
  • 0 is the initial value.

6. Updating State

The setter function is used to update state.

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

function increase() {

    setCount(count + 1);

}

Calling setCount() requests an update to the state.

7. useState with a Button

import { useState } from "react";

function App() {

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

    return (
        <div>

            <h1>
                {count}
            </h1>

            <button
                onClick={() =>
                    setCount(count + 1)
                }
            >
                Increase
            </button>

        </div>
    );

}

export default App;

8. Initial State

The value passed to useState() becomes the initial state.

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

const [age, setAge] = useState(20);

const [isLoggedIn, setIsLoggedIn] =
    useState(false);

9. useState with Strings

State can store string values.

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

function changeName() {

    setName("Rahul");

}

The state can then be displayed using JSX.

<h2>
    {name}
</h2>

10. useState with Numbers

Numbers can also be stored in state.

const [age, setAge] = useState(18);

function increaseAge() {

    setAge(age + 1);

}

11. useState with Boolean Values

Boolean state is useful for values such as visible/hidden, logged in/logged out, or enabled/disabled.

const [isVisible, setIsVisible] =
    useState(true);

function toggle() {

    setIsVisible(!isVisible);

}

12. Toggling Boolean State

import { useState } from "react";

function App() {

    const [visible, setVisible] = useState(true);

    return (
        <div>

            <button
                onClick={() =>
                    setVisible(!visible)
                }
            >
                Toggle
            </button>

            {visible && (
                <p>
                    This text is visible.
                </p>
            )}

        </div>
    );

}

13. useState with Arrays

An array can also be stored in state.

const [courses, setCourses] = useState([
    "HTML",
    "CSS",
    "React"
]);

The array can be displayed using map().

{courses.map(course => (
    <li key={course}>
        {course}
    </li>
))}

14. Updating an Array State

A new array can be created using the spread operator.

setCourses([
    ...courses,
    "JavaScript"
]);

This creates a new array containing the existing courses and the new course.

15. useState with Objects

Objects can be stored in state.

const [student, setStudent] = useState({
    name: "Rahul",
    age: 20,
    course: "React"
});

Object state is useful for related values.

16. Updating an Object State

When updating an object, preserve the existing properties that you want to keep.

setStudent({
    ...student,
    age: 21
});

The spread operator copies the existing properties and the new age value replaces the old one.

17. State and Input Fields

The useState Hook is commonly used to control form inputs.

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

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

18. State Updates Cause Re-rendering

When state is updated, React schedules the component to render again so the interface can reflect the new state.

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

setCount(count + 1);

The updated value can then appear in the rendered interface.

19. Never Modify State Directly

State should be updated through its setter function instead of directly modifying the state variable.

Avoid:

count = count + 1;

Prefer:

setCount(count + 1);

20. Functional State Updates

When the new state depends on the previous state, a function can be passed to the setter.

setCount(previousCount =>
    previousCount + 1
);

This form clearly expresses that the new value depends on the previous value.

21. Multiple State Variables

A component can use multiple useState Hooks.

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

const [age, setAge] = useState(18);

const [isStudent, setIsStudent] =
    useState(true);

Each state variable has its own setter function.

22. Counter with Increase and Decrease

import { useState } from "react";

function App() {

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

    function increase() {

        setCount(count + 1);

    }

    function decrease() {

        setCount(count - 1);

    }

    return (
        <div>

            <h1>
                {count}
            </h1>

            <button onClick={increase}>
                +
            </button>

            <button onClick={decrease}>
                -
            </button>

        </div>
    );

}

export default App;

23. Resetting State

The setter function can also be used to return state to its initial value.

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

function reset() {

    setCount(0);

}

24. State and Conditional Rendering

Boolean state can control whether an element is displayed.

const [loggedIn, setLoggedIn] =
    useState(false);

return (
    <div>

        {loggedIn ? (
            <h2>
                Welcome User
            </h2>
        ) : (
            <h2>
                Please Login
            </h2>
        )}

    </div>
);

25. State and Event Handlers

State is often changed as a result of user events.

function handleClick() {

    setCount(count + 1);

}

<button onClick={handleClick}>
    Increase
</button>

The event handler calls the state setter.

26. Lazy Initial State

If calculating the initial state requires work, a function can be passed to useState.

const [value, setValue] = useState(() => {
    return calculateInitialValue();
});

React can use the function to obtain the initial value.

27. State Update Based on Previous State

When multiple updates depend on the previous value, use the updater function form.

setCount(previousCount =>
    previousCount + 1
);

setCount(previousCount =>
    previousCount + 1
);

This makes each update explicitly depend on the previous state value.

28. Complete useState Example

import { useState } from "react";

function App() {

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

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

    function increase() {

        setCount(previousCount =>
            previousCount + 1
        );

    }

    function reset() {

        setCount(0);

    }

    return (
        <div>

            <h1>
                Counter: {count}
            </h1>

            <button onClick={increase}>
                Increase
            </button>

            <button onClick={reset}>
                Reset
            </button>

            <br />

            <input
                value={name}
                onChange={(e) =>
                    setName(e.target.value)
                }
                placeholder="Enter name"
            />

            <h2>
                Hello {name}
            </h2>

        </div>
    );

}

export default App;

29. Common useState Mistakes

  • Forgetting to import useState.
  • Calling Hooks conditionally.
  • Trying to modify state directly.
  • Using the wrong setter function.
  • Mutating arrays or objects directly.
  • Forgetting to preserve object properties when needed.
  • Using the current value when a previous-state update is more appropriate.

Example of direct modification to avoid:

student.age = 21;

Prefer:

setStudent({
    ...student,
    age: 21
});

30. useState Best Practices

  • Use useState for data that changes over time.
  • Choose meaningful state variable names.
  • Use the setter function to update state.
  • Do not directly mutate state.
  • Use functional updates when the new state depends on the previous state.
  • Use arrays and objects carefully when updating state.
  • Keep related state organized.
  • Use state to control interactive UI elements.
  • Keep state as simple as practical.
  • Remember that state updates cause React to render the component again.

📌 Key Points

  • useState is a React Hook for managing component state.
  • It returns the current state value and a setter function.
  • The setter function is used to update state.
  • State can contain strings, numbers, booleans, arrays, and objects.
  • State updates cause React to render the component again.
  • State should not be modified directly.
  • Use functional updates when the next value depends on the previous value.
  • Multiple useState Hooks can be used in one component.
  • State is commonly used with forms and event handlers.
  • Boolean state is useful for toggling UI elements.

🧠 Quick Quiz

Question: What is the main purpose of the useState Hook in React?