Popular Searches
Popular Course Categories
Popular Courses

useState Hook

useState Hook

React Hooks Fundamentals

useState Hook in React JS

useState is a built-in React Hook that allows function components to store, remember, and update data between renders. It is one of the most commonly used Hooks in React and is essential for creating interactive user interfaces.

For example, useState can manage a counter value, a user's name, form inputs, a checkbox, a shopping cart, a selected product, or the visibility of a menu.

Course: JustAcademy React JS Training

Course Demo: Register for React JS Course Demo


1. Learning Objectives

After studying this topic, you will be able to:

  • Understand the meaning and purpose of the useState Hook.
  • Learn the syntax and working of useState.
  • Create and update state variables.
  • Manage numbers, strings, booleans, arrays, and objects using state.
  • Handle user interactions with state.
  • Understand functional state updates and state batching.
  • Use useState with forms and conditional rendering.
  • Identify common mistakes and follow best practices.

2. What Is the useState Hook?

The useState Hook is a React function that adds a state variable to a function component. State is information that React remembers between renders and uses to determine what should appear on the screen.

When state changes through its setter function, React schedules a re-render so the component can display the updated value.

Example

import { useState } from "react";
function Greeting() {
  const [name, setName] = useState("Alex");
  return (
    <div>
      <h2>Hello, {name}!</h2>
      <button onClick={() => setName("Jordan")}>
        Change Name
      </button>
    </div>
  );
}
export default Greeting;

Explanation:

  • The initial value of name is "Alex".
  • setName updates the name state.
  • Clicking the button changes the name to "Jordan".
  • React renders the updated greeting.

3. Why Do We Need useState?

Regular JavaScript variables are not enough when a component needs to remember information and automatically display changes after an interaction. React state provides a way to store such information and request UI updates when it changes.

Common Uses

  • Counter applications: Store the current count.
  • Forms: Store names, email addresses, passwords, and other input values.
  • Toggle buttons: Track whether a feature is enabled or disabled.
  • Conditional rendering: Show or hide menus, modals, and messages.
  • Shopping carts: Store products and quantities.
  • Tabs and navigation: Track the selected tab or active section.
  • Data displays: Store results received from an API.
  • Interactive interfaces: Remember the selected image, rating, or filter.

Regular Variable vs State Variable

Regular Variable State Variable
Declared using let or const. Declared using a Hook such as useState.
Does not persist as component state between renders. React remembers its value between renders.
Changing it does not automatically trigger a React re-render. Updating it with its setter can trigger a re-render.
Useful for temporary calculations inside a render or function. Useful for information that affects the rendered UI.

4. Syntax of the useState Hook

The general syntax of useState is:

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

Understanding Each Part

  • useState: The React Hook that declares a state variable.
  • initialValue: The initial state value used during the component's initialization.
  • state: The current state value for the render.
  • setState: The function used to request a state update.

The Hook returns an array containing two values. JavaScript array destructuring assigns these values to the state variable and its setter function.

Importing useState

import { useState } from "react";

You must import useState from React when using this named-import style.

Example

import { useState } from "react";
function Example() {
  const [age, setAge] = useState(20);
  return (
    <div>
      <p>Age: {age}</p>
      <button onClick={() => setAge(age + 1)}>
        Increase Age
      </button>
    </div>
  );
}
export default Example;

In this example, age begins at 20. Clicking the button requests a new state value of 21, then 22, and so on.


5. How Does useState Work?

React uses state to remember information associated with a component. The initial value is used when that component instance is initialized. On later renders, React returns the current stored state and the setter function.

Step-by-Step Process

  1. Import the Hook: Import useState from React.
  2. Declare the state: Call useState at the top level of the component.
  3. Set the initial value: Provide a suitable starting value.
  4. Display the state: Use the state variable in JSX.
  5. Handle interaction: Call the setter function when a user performs an action.
  6. Re-render: React renders the component again with the updated state when needed.
  7. Update the UI: React updates the rendered output to reflect the new state.

Example: A Simple Counter

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;

Initial output: Count: 0

After one click: Count: 1

After two clicks: Count: 2


6. Managing Different Data Types with useState

The useState Hook can store values of different JavaScript data types, including numbers, strings, booleans, arrays, objects, and even functions.

6.1 Number State

Number state is commonly used for counters, quantities, scores, and numeric values.

import { useState } from "react";
function Score() {
  const [score, setScore] = useState(0);
  return (
    <div>
      <p>Score: {score}</p>
      <button onClick={() => setScore(score + 10)}>
        Add 10 Points
      </button>
    </div>
  );
}
export default Score;

6.2 String State

String state is useful for names, messages, search terms, and input fields.

import { useState } from "react";
function NameInput() {
  const [name, setName] = useState("");
  return (
    <div>
      <input
        value={name}
        onChange={event => setName(event.target.value)}
        placeholder="Enter your name"
      />
      <p>Your name is: {name}</p>
    </div>
  );
}
export default NameInput;

The input is controlled by React because its value comes from state and its onChange handler updates that state.

6.3 Boolean State

Boolean state stores either true or false. It is useful for toggles, menus, modals, and visibility controls.

import { useState } from "react";
function ToggleMessage() {
  const [isVisible, setIsVisible] = useState(false);
  return (
    <div>
      <button onClick={() => setIsVisible(value => !value)}>
        {isVisible ? "Hide Message" : "Show Message"}
      </button>
      {isVisible && <p>Welcome to React JS!</p>}
    </div>
  );
}
export default ToggleMessage;

6.4 Array State

Array state can store lists of items, such as tasks, products, notifications, or student names. When updating an array, create a new array rather than modifying the existing one.

import { useState } from "react";
function TodoList() {
  const [todos, setTodos] = useState(["Learn HTML", "Learn CSS"]);
  function addTodo() {
    setTodos(previousTodos => [...previousTodos, "Learn React"]);
  }
  return (
    <div>
      <ul>
        {todos.map((todo, index) => (
          <li key={`${todo}-${index}`}>{todo}</li>
        ))}
      </ul>
      <button onClick={addTodo}>Add Todo</button>
    </div>
  );
}
export default TodoList;

The spread operator creates a new array containing the existing tasks and the new task. In production lists, use stable unique IDs for React keys whenever possible.

6.5 Object State

Object state is useful for managing related information, such as user details, product data, and form values.

import { useState } from "react";
function UserProfile() {
  const [user, setUser] = useState({
    name: "Alex",
    age: 22
  });
  function updateAge() {
    setUser(previousUser => ({
      ...previousUser,
      age: previousUser.age + 1
    }));
  }
  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <button onClick={updateAge}>Increase Age</button>
    </div>
  );
}
export default UserProfile;

The spread operator copies the existing properties, and the new age value replaces the previous one. This preserves the user's name.


7. Updating State Using the Setter Function

The setter function returned by useState requests an update to the state variable. You can pass either the next value directly or an updater function that calculates the next value from the previous state.

Method 1: Pass the Next Value

const [count, setCount] = useState(0);
function increaseCount() {
  setCount(count + 1);
}

This approach is suitable when calculating the next value from the current render's state is sufficient.

Method 2: Use a Functional State Update

const [count, setCount] = useState(0);
function increaseCount() {
  setCount(previousCount => previousCount + 1);
}

This approach is useful when the next state depends on the previous state. React passes the pending state to the updater function and uses the returned value as the next state.

Example: Increment Three Times

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  function increaseThreeTimes() {
    setCount(previous => previous + 1);
    setCount(previous => previous + 1);
    setCount(previous => previous + 1);
  }
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increaseThreeTimes}>Increase by 3</button>
    </div>
  );
}
export default Counter;

Clicking the button increases the count by three because each updater calculates its result from the preceding queued state update.


8. State Updates and Re-Rendering

When you call a state setter, React schedules an update. React then renders the component with the new state and updates the UI as needed.

Important Concept: State Is a Snapshot

The state variable inside the currently running event handler remains the value from that render. Calling the setter does not immediately change that variable in the already executing code.

import { useState } from "react";
function Example() {
  const [count, setCount] = useState(0);
  function handleClick() {
    setCount(count + 1);
    console.log(count);
  }
  return <button onClick={handleClick}>Count: {count}</button>;
}
export default Example;

When the button is clicked for the first time, the log can show 0, while the next render displays 1. This is expected because the handler reads the state snapshot from the render in which it was created.

React Batches State Updates

React often groups state updates that occur during the same event handler and updates the UI after the handler finishes. This behavior is called batching. Use functional state updates when several updates depend on earlier queued updates.


9. Using Multiple useState Hooks

A component can declare multiple state variables to manage different pieces of information independently.

Example: User Details

import { useState } from "react";
function UserDetails() {
  const [name, setName] = useState("");
  const [age, setAge] = useState("");
  const [city, setCity] = useState("");
  return (
    <div>
      <input
        value={name}
        onChange={event => setName(event.target.value)}
        placeholder="Enter name"
      />
      <input
        value={age}
        onChange={event => setAge(event.target.value)}
        placeholder="Enter age"
      />
      <input
        value={city}
        onChange={event => setCity(event.target.value)}
        placeholder="Enter city"
      />
      <h3>User Information</h3>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>City: {city}</p>
    </div>
  );
}
export default UserDetails;

Each state variable stores a different value. Updating the name does not automatically overwrite the age or city.


10. Using useState with Forms

The useState Hook is commonly used to manage form inputs. In a controlled input, React state stores the current value and the input's onChange handler updates it.

Example: Registration Form

import { useState } from "react";
function RegistrationForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [submitted, setSubmitted] = useState(false);
  function handleSubmit(event) {
    event.preventDefault();
    setSubmitted(true);
  }
  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input
          value={name}
          onChange={event => setName(event.target.value)}
          required
        />
      </label>
      <label>
        Email:
        <input
          type="email"
          value={email}
          onChange={event => setEmail(event.target.value)}
          required
        />
      </label>
      <button type="submit">Register</button>
      {submitted && (
        <p>Thank you, {name}! Your form was submitted.</p>
      )}
    </form>
  );
}
export default RegistrationForm;

Explanation

  • name stores the name input value.
  • email stores the email input value.
  • submitted tracks whether the form was submitted.
  • onChange handlers keep the inputs synchronized with state.
  • event.preventDefault() prevents the browser's default form navigation.

This example demonstrates client-side UI behavior only. A real registration system should also validate data and securely process it on the server.


11. Updating Objects and Arrays Correctly

React state should be treated as read-only. Do not directly modify objects or arrays already stored in state. Instead, create a new object or array and pass it to the setter.

Incorrect Object Update

user.age = 25;
setUser(user);

This mutates the existing object and passes the same reference back to React. React may skip rendering because the new value is identical to the previous value by reference.

Correct Object Update

setUser(previousUser => ({
  ...previousUser,
  age: 25
}));

Incorrect Array Update

items.push("New Item");
setItems(items);

Correct Array Update

setItems(previousItems => [...previousItems, "New Item"]);

For removing an item, use methods such as filter() to create a new array. For updating an item, use methods such as map() to create a new array with the required change.


12. Lazy Initialization with useState

React uses the initial state value only when initializing a component instance. If calculating that initial value is expensive, pass an initializer function instead of calling the calculation directly on every render.

Direct Initialization

const [items, setItems] = useState(createInitialItems());

The expression createInitialItems() runs whenever the component function executes, even though React only uses the returned initial value during initialization.

Lazy Initialization

const [items, setItems] = useState(createInitialItems);

Here, React calls the initializer function to obtain the initial state. The initializer should be pure and should not perform side effects.

Complete Example

import { useState } from "react";
function createInitialItems() {
  return ["HTML", "CSS", "JavaScript"];
}
function CourseList() {
  const [courses, setCourses] = useState(createInitialItems);
  return (
    <ul>
      {courses.map(course => (
        <li key={course}>{course}</li>
      ))}
    </ul>
  );
}
export default CourseList;

In development Strict Mode, React may call initializer functions more than once to help detect accidental impurities. Keep the initializer pure so this does not affect the result.


13. Resetting State

State can be reset by calling its setter with the desired initial value.

Example: Reset a Counter

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(c => c + 1)}>Increase</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}
export default Counter;

For more complex cases, changing a component's key can make React create a new component instance and reset its state. Use this approach when a complete component-state reset is appropriate.


14. Rules of the useState Hook

The useState Hook must follow the Rules of Hooks.

  1. Call at the top level: Do not call useState inside conditions, loops, or nested functions.
  2. Use function components or custom Hooks: Do not call it directly inside class components or ordinary JavaScript functions.
  3. Do not call it in event handlers: Declare the Hook at the top level and call its setter from event handlers.
  4. Do not mutate state: Replace objects and arrays rather than modifying them directly.
  5. Use the setter to update state: Changing a local variable does not update React state.
  6. Keep updater functions pure: An updater should calculate and return the next state without causing side effects.
  7. Use suitable initial values: Initialize controlled text inputs with a string such as "" instead of null or undefined.

15. Common Mistakes and Solutions

Common Mistake Why It Is a Problem Correct Approach
Updating a regular variable instead of state. React is not notified of the change. Use a state setter for values that affect the UI.
Calling useState inside an if statement. Hook call order can change between renders. Call the Hook at the top level.
Mutating an object or array in state. The existing reference is modified. Create a new object or array.
Expecting the state variable to change immediately after setting it. The current render uses a state snapshot. Use the next render to read the updated value.
Calling a setter while rendering without a guarded pattern. Can create an infinite re-render loop. Update state in event handlers or use the appropriate state-management pattern.
Using value={undefined} for a controlled text input. The input may switch between controlled and uncontrolled modes. Initialize the input value with a string.
Using a direct update for multiple dependent updates. Updates can be calculated from the same render snapshot. Use functional updates when the next state depends on the previous state.
Putting side effects inside an updater function. Updater functions should be pure and may run more than once in development. Perform side effects in event handlers or appropriate effects.

16. Best Practices for useState

  • Choose clear and meaningful names, such as count, isOpen, and userName.
  • Use the naming convention [value, setValue].
  • Use separate state variables for independent pieces of state when that makes the code easier to understand.
  • Use an object or reducer when several values are closely related or transitions are complex.
  • Use functional updates when the next value depends on the previous value.
  • Keep state updates immutable, especially for arrays and objects.
  • Do not store a value in state if it can be calculated directly from existing props or state without creating synchronization problems.
  • Use lazy initialization for expensive initial calculations.
  • Keep updater functions pure.
  • Use React Developer Tools to inspect state and troubleshoot rendering issues.

17. Practical Project: Shopping Cart Quantity

Build a simple shopping cart quantity component using useState. The user can increase or decrease the number of items, and the component calculates the total price.

Project Requirements

  • Display the product name and unit price.
  • Start the quantity at 1.
  • Increase the quantity when the user clicks Add One.
  • Decrease the quantity without allowing it to fall below 1.
  • Calculate the total price from the current quantity.
  • Reset the quantity to 1.

Complete Code

import { useState } from "react";
function ShoppingCart() {
  const [quantity, setQuantity] = useState(1);
  const unitPrice = 500;
  const totalPrice = quantity * unitPrice;
  function increaseQuantity() {
    setQuantity(previousQuantity => previousQuantity + 1);
  }
  function decreaseQuantity() {
    setQuantity(previousQuantity =>
      Math.max(1, previousQuantity - 1)
    );
  }
  function resetQuantity() {
    setQuantity(1);
  }
  return (
    <div>
      <h2>Shopping Cart</h2>
      <p>Product: React JS Book</p>
      <p>Unit Price: ₹{unitPrice}</p>
      <p>Quantity: {quantity}</p>
      <p>Total Price: ₹{totalPrice}</p>
      <button onClick={increaseQuantity}>Add One</button>
      <button onClick={decreaseQuantity}>Remove One</button>
      <button onClick={resetQuantity}>Reset</button>
    </div>
  );
}
export default ShoppingCart;

How It Works

  1. The quantity starts at 1.
  2. Each click on Add One increases the quantity by one.
  3. Remove One decreases the quantity but never below 1.
  4. The total price is calculated from the unit price and quantity.
  5. Reset returns the quantity to 1.

This project demonstrates numeric state, functional state updates, event handling, derived values, and conditional limits.


18. Interview Questions and Answers

Q1. What is the useState Hook in React?

Answer: useState is a built-in React Hook that allows function components to store and update state between renders.

Q2. What does useState return?

Answer: It returns an array containing the current state value and a setter function.

Q3. What is the syntax of useState?

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

Q4. What happens when a state setter is called?

Answer: React schedules a state update and renders the component again when needed to reflect the new state.

Q5. Can a component use multiple useState Hooks?

Answer: Yes. A component can declare multiple state variables for different pieces of information.

Q6. What is a functional state update?

Answer: It passes a function to the setter, such as setCount(previous => previous + 1), to calculate the next value from the pending previous state.

Q7. Can useState store objects and arrays?

Answer: Yes. It can store values of different types. Objects and arrays should be replaced with new values rather than mutated directly.

Q8. Does calling a state setter immediately change the current state variable?

Answer: No. The current render uses its existing state snapshot. The new value is available in a subsequent render.

Q9. What is lazy initialization?

Answer: Lazy initialization passes an initializer function to useState, allowing React to call it to calculate the initial state rather than recalculating that initial value on every render.

Q10. Can useState be called inside a condition?

Answer: No. It must be called at the top level of a function component or custom Hook.

Q11. What is the difference between useState and useRef?

Answer: Updating state can trigger a re-render, while changing a ref's current property does not trigger a re-render by itself.

Q12. When should a functional state update be used?

Answer: Use it when the next state depends on the previous state or when several updates need to build on one another.


19. Practice Exercises

  1. Create a counter with Increase, Decrease, and Reset buttons.
  2. Build a text input that displays the entered name immediately.
  3. Create a dark/light mode toggle using boolean state.
  4. Build a registration form that stores a name and email address.
  5. Create a todo list that can add and remove tasks using array state.
  6. Create a user profile object and update one property without losing the other properties.
  7. Build a product quantity selector with a minimum quantity of one.
  8. Create a show/hide password button using state.
  9. Implement a lazy initializer for a list of initial tasks.
  10. Demonstrate why reading a state variable immediately after calling its setter returns the current render's value.

20. Quick Revision

  • useState: A React Hook used to add state to a function component.
  • Initial state: The value used to initialize the state variable.
  • State variable: The current value returned by the Hook for a render.
  • Setter function: Requests an update to the state.
  • Re-rendering: React renders the component again when a state update requires it.
  • Functional update: Calculates the next value from the pending previous state.
  • Immutable update: Creates a new array or object instead of mutating existing state.
  • Lazy initialization: Passes an initializer function to calculate the initial state.
  • Rules of Hooks: Call useState at the top level of a function component or custom Hook.

21. Conclusion

The useState Hook is a foundation of modern React development. It enables components to remember information, respond to user interactions, control form fields, display conditional content, and manage dynamic lists.

To use it effectively, understand the state setter, use functional updates when needed, avoid directly mutating arrays and objects, and follow the Rules of Hooks. Practice with counters, forms, toggles, and shopping cart projects to strengthen your understanding.

Continue learning through JustAcademy React JS Training or Register for React JS Course Demo.

22. Official React Documentation

Previous Next
whatsapp