Changes in Data

The core problem is: how do you manage data that changes over time, and how do you tell React to update the UI when that data changes?

The Problem: Static Components

Without a tool to handle it, a React component is essentially static. It renders once with its initial data, and that’s it. If a user clicks a button to increment a counter, there’s no built-in way to get the component to “remember” the new count and update the screen. The UI would stay frozen at its original state.

This is where state comes in. State is simply data that a component can remember and manage.

The Solution: The useState Hook

The useState hook is the simplest and most common way to add state to your functional components. It provides a special variable that React can “watch.” When this variable is updated, React automatically knows it needs to re-render the component to reflect the new information.

Think of it like a small, dedicated whiteboard for your component.

  • The initial value you give to useState is what you write on the whiteboard first.
  • The state variable is whatever is currently written on the board.
  • The setter function is like your marker and eraser. It’s the only way to change what’s on the whiteboard. When you use this function, React sees the change and automatically updates the component.

This is the most important part: you should never change the state variable directly. You must use the setter function provided by useState to tell React that a change is happening.

How to Use useState

The syntax for useState is simple

const [stateVariable, setStateFunction] = useState(initialValue);

Let’s break it down with a classic example: a simple counter.

import React, { useState } from 'react';

function Counter() {
  // 1. `count` is the state variable. Its initial value is 0.
  // 2. `setCount` is the function we use to update `count`.
  const [count, setCount] = useState(0);

  const increment = () => {
    // 3. We call the setter function to update the state.
    // React will re-render the component with the new value of `count`.
    setCount(count + 1);
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={increment}>
        Click Me
      </button>
    </div>
  );
}

By using useState, we’ve given our component a memory. It can now track the count and update the UI automatically every time the user clicks the button. This frees you from having to manually manipulate the DOM, making your code simpler, more predictable, and easier to manage.