DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

Understanding `useState` in React

What Problem Does useState Solve?

Before React, changing something on the screen meant:

  • Finding the HTML element
  • Manually updating it
  • Making sure nothing else breaks

React changes this completely.

React says:

“Tell me what the UI should look like for a given state, and I’ll handle updates.”

To do that, React needs a way to store changing data.
That’s where useState comes in.


What Is useState?

useState is a React Hook that lets a component:

  • Store data
  • Update that data
  • Automatically re-render the UI when the data changes

In simple terms:

useState is how React remembers values.


Basic Example

import { useState } from "react";

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

  return (
    <>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Breaking It Down Slowly

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

This line does three things:

  1. Creates a state variable → count
  2. Creates a function to update it → setCount
  3. Sets the initial value → 0

Think of it like backend code:

let count = 0;

function setCount(newValue) {
  count = newValue;
}
Enter fullscreen mode Exit fullscreen mode

Except React also updates the UI automatically.


Why You Must Use the Setter Function

❌ This will NOT work correctly:

count = count + 1;
Enter fullscreen mode Exit fullscreen mode

✅ This is correct:

setCount(count + 1);
Enter fullscreen mode Exit fullscreen mode

Why?

  • React tracks state changes through the setter
  • Direct mutation bypasses React
  • No re-render happens

When to Use useState

Use useState when:

  • Data changes based on user interaction
  • UI should update when data changes

Examples:

  • Form inputs
  • Toggle switches
  • Counters
  • Loading states
  • Modal open/close

Key Takeaway

useState lets your component remember data and react to changes.

Master this first. Everything else depends on it.

Top comments (1)

Collapse
 
a-k-0047 profile image
ak0047

Really clear and beginner friendly article — thank you!