Introduction to State in React: Your Component's Memory

Give your components a memory and unlock the power to build dynamic, interactive applications from scratch.

🤔

Welcome! So far, our components are static. Let's give them a memory to make them interactive.

/* Giving our components a brain... */

What is State? A Component's Memory

Think of state as a component's memory. It's any piece of data that can change over time, such as user input in a form, items in a shopping cart, or whether a button is toggled. Unlike props, which are passed *into* a component, state is managed *within* the component itself.

The `useState` Hook: Adding Memory

To add state to a functional component, we use the `useState` Hook. It's a special function that you call with an initial value. It returns an array with two elements: the current state value and a function to update that value. We typically use array destructuring to get these two elements: const [count, setCount] = useState(0);.

Triggering Updates with Setter Functions

When you call the state setter function (like `setCount(1)`), you are telling React two things: 1) to update the state variable with the new value, and 2) to re-render the component. This re-render ensures that the user interface is updated to reflect the new state value. Crucially, you should never modify state directly (e.g., `count = 1`).

The Result: An Interactive UI

By using state, your components are no longer static. They can remember information, respond to user interactions like clicks and typing, and dynamically update the UI. This is the core mechanism that makes React applications interactive and powerful.

Practice Zone


Interactive Test 1: Deconstruct the Hook

Given the code `const [age, setAge] = useState(25);`, match each term to its role.

Arrastra en el orden correspondiente.


Arrastra las opciones:

setAge
useState(25)
age

Completa el código:

The current value (25)______
The function to change state______
The initial value______
Unlock with Premium

Interactive Test 2: Complete the Counter

Rellena los huecos en cada casilla.

import React, {  } from 'react';

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

  return (
    <button onClick={() => (count + 1)}>
      Clicked {count} times
    </button>
  );
}
Unlock with Premium

Practice Example: Build a Toggler

Create a component that displays "On" or "Off". When a button is clicked, the text should toggle between the two values.

Enunciado:

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

function Toggle() { const [isOn, setIsOn] = useState(false); return ( <div> <p>{isOn ? 'On' : 'Off'}</p> <button onClick={() => setIsOn(!isOn)}> Toggle </button> </div> ); }

Unlock with Premium

Knowledge Check

What does the `useState` hook return?


Unlock with Premium

State in Action

State is the heartbeat of any interactive React application. Let's explore how it interacts with other essential React concepts to bring your UI to life.


1. State and User Input: Controlled Components

A common pattern is to connect a form input's value directly to a piece of state. This makes the React component the "single source of truth" for the input's value. Every keystroke calls the state setter, updating the state and re-rendering the input with the new value.

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

// ...

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

UI is in sync with state.

2. State vs. Props: A Clear Distinction

This is a crucial concept. Props are for passing data down from a parent to a child component (one-way data flow). State is for managing a component's own internal data that changes over time. A component cannot change its own props, but it can always change its own state.

Props 📥

Data passed in from parent.
Read-only.

State 🧠

Internal memory.
Can be changed by the component itself.

3. Managing Complex State (Objects & Arrays)

State doesn't have to be a simple string or number. It can be an object or an array. When updating them, it's vital to follow the principle of immutability—never modify the existing state directly. Instead, create a new object or array with the updated values using syntax like the spread operator (`...`).

// Add a new item to an array in state
setItems([...items, newItem]);

// Update a property in an object in state
setUser({ ...user, name: 'New Name' });
Creating new copies, not mutating.

Practical Takeaway: Think of `useState` as giving your component a superpower: the ability to remember things and react when those memories change. It is the fundamental building block for all interactivity in React.

React State Glossary

State
A JavaScript object that holds data that may change over the lifetime of a React component. It represents the component's "memory" and determines its rendered output.
Hook
Special functions, like `useState`, that let you "hook into" React features from functional components. They always start with the word "use".
`useState`
The React Hook that lets you add state to functional components. It returns the current state value and a function to update it.
Re-render
The process of React calling a component's function again to update the UI. This happens automatically when a component's state or props change.
Immutability
The principle of not changing data or objects directly. When updating state, you should create a new copy with the changes rather than modifying the original state variable.