Making Components Interactive with the useState Hook
Give your components a memory and bring your user interfaces to life with the fundamental `useState` Hook.
import React, { useState } from 'react';
What is State? A Component's Memory
State is like a component's memory. It's data that can change over time due to user interaction or other events. When a component's state changes, React knows it needs to update the screen to reflect that change.
Declaring State with useState
To add state to a functional component, we use the useState
Hook. It returns a pair of values: the current state value and a function to update it. Example: const [count, setCount] = useState(0);
. Here, count
is our state variable (initially 0), and setCount
is the function we'll use to change it.
Updating State Correctly
You must never modify state directly (e.g., `count = 1`). Always use the setter function provided by `useState` (e.g., setCount(1)
). Calling this function tells React that the state has changed and that the component needs to be re-rendered to display the new value.
The Result: Automatic Re-Renders
When the setter function (like setCount
) is called, React schedules a re-render of your component. During the re-render, the useState
hook provides the new, updated value. This seamless process makes your user interface interactive and always in sync with your application's data.
Practice Zone
Interactive Test 1: Deconstruct State
You have the code const [age, setAge] = useState(25);
. Match each part to its correct description.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
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)}> You clicked {count} times </button> ); }
Practice Example: Code Editor
Create a component that displays a text message. Add a button that, when clicked, changes the text from "Hello" to "Goodbye".
State in Action: Advanced Usage
`useState` is versatile. You can use it for more than just numbers and strings. Here are some common patterns you'll encounter in real-world applications.
1. Multiple State Variables
A single component can (and often will) have multiple state variables. Each one controls a different piece of data. This keeps your logic clean and separated.
function UserProfile() {
const [username, setUsername] = useState('Guest');
const [theme, setTheme] = useState('light');
const [notifications, setNotifications] = useState(true);
// ...
}
2. Managing Objects in State
When your state is an object, remember that state updates must replace the old object with a new one. The spread syntax (`...`) is perfect for this, as it creates a new object while copying over the old properties.
const [user, setUser] = useState({ name: 'Alice', age: 30 });
// Correct way to update one property:
const handleAgeUp = () => {
setUser({ ...user, age: user.age + 1 });
}
3. Functional Updates for Reliability
If your new state depends on the previous state, it's safer to pass a function to your setter. This function receives the previous state and returns the new one. It prevents bugs related to "stale" state in asynchronous operations.
// Safe way to update a counter
setCount(prevCount => prevCount + 1);
// Unsafe way, especially with rapid clicks
// setCount(count + 1);
Practical Takeaway: State is the engine of interactivity in React. By understanding how to manage numbers, objects, and how to update state safely, you can build reliable and complex user interfaces.
`useState` Glossary
- State
- Any data that a component "remembers" and that can change over time. When state changes, the component re-renders to reflect the new data.
- Hook
- Special JavaScript functions, like `useState` or `useEffect`, that let you "hook into" React features (like state and lifecycle) from within functional components.
- `useState`
- The React Hook that allows you to declare a state variable inside a functional component. It returns an array with two items: the state variable and a function to update it.
- Initial State
- The value you pass to `useState` the first time a component renders (e.g., the `0` in `useState(0)`). This is the state's starting value.
- Re-render
- The process where React calls your component function again to compute the new UI. This is automatically triggered when you update state using the setter function.
- Setter Function
- The second item returned by `useState` (e.g., `setCount`). It's the only correct way to update a piece of state and trigger a re-render.