DEV Community

Harini
Harini

Posted on • Edited on

What is useState in React? Explained with Practical Examples

What is useState?

useState is a React Hook that allows functional components to manage state. It returns a state variable and a setter function. When the setter function is called, React re-renders the component with updated state.

Basic Syntax:

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

  • state β†’ Current value

  • setState β†’ Function to update the value

  • initialValue β†’ Starting value

Why Do We Need useState?

React components re-render when state changes.

Without state:

  • No dynamic UI

  • No user interaction handling

  • No form handling

  • No toggle functionality

State makes your UI interactive.

Example 1: Counter

import { useState } from "react";

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

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;

**What Happens Here?**
Enter fullscreen mode Exit fullscreen mode
  1. Initial value is 0

  2. When button is clicked

  3. setCount(count + 1) runs

  4. React updates state

  5. Component re-renders

  6. UI updates automatically

Example 2: Toggle Button

import { useState } from "react";

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

  return (
    <div>
      <h2>{isOn ? "Light ON πŸ’‘" : "Light OFF πŸŒ™"}</h2>
      <button onClick={() => setIsOn(!isOn)}>
        Toggle
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Here:

  • false β†’ Initial state

  • Clicking button flips the value

  • UI updates instantly

This pattern is used in:

  • Dark mode toggle

  • Show/Hide password

  • Dropdown menus

  • Modal open/close

Top comments (0)