The useState Hook: Managing State in React

Give your components a memory. Learn to manage dynamic data and build interactive UIs with React's fundamental hook.

Count: 0

Welcome! Let's learn how React components can remember information.

/* How do we make this count interactive? */

What is State?

In React, state is any data that your component "remembers" and that can change over time. Think of it as a component's personal memory. When this data changes, React knows it needs to update what's shown on the screen.

The `useState` Hook Syntax

The `useState` hook is React's function for adding state to functional components. You call it at the top of your component to declare a state variable. It returns an array with two things: the current state value and a function to update that value. The syntax is: const [count, setCount] = useState(0);

How to Update State

To change the state, you must use the special setter function that `useState` gives you (like `setCount`). Directly changing the state variable (e.g., `count = 1`) will not work because React won't know that it needs to update the UI. Always use the setter function: setCount(newCount).

The Result: A UI Re-render

When you call the setter function, you're telling React, "Hey, this important data has changed!" React then automatically re-renders your component. This means React runs your component's code again with the new state value and updates the DOM to match the new output, making your UI interactive.

Practice Zone


Interactive Test 1: Drag and Drop

Complete the code to create a simple counter.

Arrastra en el orden correspondiente.


Arrastra las opciones:

useState
setState

Completa el código:

const [state, setState] = ______(0);
<button onClick={() => ______(state + 1)}>Increment</button>
Unlock with Premium

Interactive Test 2: Complete the Code

Fill in the blanks to correctly use the `useState` hook.

Rellena los huecos en cada casilla.

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => (count + 1)}>
        Click me
      </button>
    </div>
  );
}
Unlock with Premium

Practice Example: Code Editor

Build a component that toggles a message's visibility. Create a state variable `isVisible` and a button to change its value between `true` and `false`. Show the message only when `isVisible` is `true`.

Enunciado:

This demonstrates using a boolean state to conditionally render an element. The `setIsVisible(!isVisible)` pattern is a common and concise way to toggle a boolean value.

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

import React, { useState } from 'react'; function ToggleMessage() { const [isVisible, setIsVisible] = useState(true); return ( <div> <button onClick={() => setIsVisible(!isVisible)}> {isVisible ? 'Hide' : 'Show'} Message </button> {isVisible && <p>Here is the secret message!</p>} </div> ); }

Unlock with Premium

Knowledge Check

What does the `useState` hook return?


Unlock with Premium

`useState` in Action

`useState` is the cornerstone of interactivity in React. Let's see how it's used in common, real-world scenarios beyond a simple counter.


1. Handling Form Inputs

To build controlled components, you use a state variable to hold the value of an input field. The `onChange` event calls the setter function to update the state with every keystroke, keeping your state and the UI perfectly in sync.

const [name, setName] = useState('');

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

2. Toggling UI Elements

A boolean state variable is perfect for showing or hiding elements like modals, dropdowns, or navigation menus. A single button can toggle the state, and conditional rendering will do the rest.

const [isOpen, setIsOpen] = useState(false);

<button onClick={() => setIsOpen(!isOpen)}>
  Toggle Menu
</button>
{isOpen && <Menu />}

3. Managing Complex State with Objects

State doesn't have to be a simple string or number. You can store objects in state. When updating, it's crucial to create a *new* object using the spread syntax (`...`) to ensure React detects the change.

const [user, setUser] = useState({ name: 'Alex', age: 30 });

const handleAgeUp = () => {
  setUser({ ...user, age: user.age + 1 });
};
name: 'Alex', age: 30

Practical Takeaway: From simple toggles to complex forms, `useState` is the fundamental building block you'll use in every interactive component you create. Mastering it is the first major step to becoming a proficient React developer.

`useState` Glossary

State
Data that a component manages internally. When state changes, the component re-renders to reflect those changes.
Hook
Special functions, like `useState` or `useEffect`, that let you use React features (like state and lifecycle) in functional components.
`useState(initialValue)`
The React Hook used to add state to a functional component. It takes an initial state value as an argument.
State Variable
The first value in the array returned by `useState`. It holds the current state. Example: `count` in `const [count, setCount] = useState(0);`.
Setter Function
The second value in the array returned by `useState`. It's the only correct way to update the state variable and trigger a re-render. Example: `setCount`.
Re-render
The process where React runs a component's function again to compute the new UI after its state or props have changed.