useState Hook

🪝 Introduction to useState

The useState Hook is one of the most commonly used React Hooks. It allows a functional component to store and update state. Whenever the state changes, React automatically re-renders the component so the user interface reflects the latest data.

Important

useState should be used whenever a component needs to remember information such as user input, counters, toggles, or selected values.

🎯 Why Use useState?

Before Hooks, only class components could manage state. The introduction of useState made it possible for functional components to store and update state without using classes.

  • Store values that change over time.
  • Automatically update the UI when state changes.
  • Keep components simple and readable.
  • Eliminate the need for class components in many cases.

⚙️ Syntax

Basic Syntax

const [state, setState] = useState(initialValue);
PartDescription
stateThe current value stored by React.
setStateA function used to update the state.
initialValueThe value assigned during the first render.

🔄 How useState Works

Component Renders
useState() Creates Initial State
User Interacts with the UI
setState() Updates the State
React Re-renders the Component
Updated UI Appears

💻 Example 1: Counter

Counter Example

import { useState } from "react";

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

  return (
    <>
      <h2>{count}</h2>

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

Initially, count is 0. Clicking the button calls setCount(), which updates the value and causes React to render the component again with the new count.

📝 Example 2: Managing Text Input

Input Example

import { useState } from "react";

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

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

      <p>Hello, {name}</p>
    </>
  );
}

The input field is controlled by the name state. Every keystroke updates the state, and the greeting changes immediately.

🎨 Example 3: Toggle Button

Boolean State

import { useState } from "react";

function Toggle() {
  const [isOn, setIsOn] = useState(false);

  return (
    <button onClick={() => setIsOn(!isOn)}>
      {isOn ? "ON" : "OFF"}
    </button>
  );
}

Boolean values are commonly used with useState to control visibility, switches, and toggle buttons.

📊 Types of State Values

Data TypeExample Initial ValueTypical Use
Number0Counters, scores
String""User input, names
BooleanfalseToggles, modals
Array[]Lists of items
ObjectUser profiles, settings

🧠 Updating State Correctly

Updating Primitive Values

Updating a Number

setCount(count + 1);

Updating Objects

Updating an Object

setUser({
  ...user,
  age: 26
});

Updating Arrays

Updating an Array

setItems([
  ...items,
  "New Item"
]);

Warning

Avoid modifying objects or arrays directly. Instead, create a new object or array before updating the state.

⚡ Functional State Updates

When the next state depends on the previous state, pass a function to setState(). This ensures React uses the latest available state value.

Functional Update

setCount(previousCount => previousCount + 1);

Best Practice

Use functional updates when multiple state updates may happen in quick succession.

📋 Common Use Cases

Store form fields such as names, email addresses, and passwords using useState.

Maintain scores, likes, quantities, and other numeric values.

Show or hide dialogs, menus, and sections using boolean state.

Manage collections of data such as shopping carts, todo lists, and notifications.

🚫 Common Mistakes

  • Updating state directly instead of using the setter function.
  • Mutating arrays or objects instead of creating new ones.
  • Expecting state updates to happen immediately after calling the setter.
  • Using too many separate state variables when related values could be grouped.

✅ Best Practices

  • Choose meaningful names for state variables.
  • Keep state as small as possible.
  • Use functional updates when relying on previous state.
  • Store only data that changes over time.
  • Never mutate state directly.

📚 Official Resource

Learn more about useState in the official React documentation at React useState Documentation.

Summary

The useState Hook enables functional components to manage state in a simple and efficient way. It stores values, updates them through a setter function, and automatically re-renders the component whenever the state changes. Mastering useState is the first step toward building interactive, dynamic, and modern React applications.