React State
Learn React State to make your components remember and update information.
State lets your component remember information and update it. Think of it like a component's memory!
What is State?
State is data that can change in your component. When state changes, React automatically updates what shows on the screen.
**Example:** A counter button needs to remember how many times it was clicked. That number is stored in state!
Using State
To use state, we need the `useState` hook:
```javascript import { useState } from 'react';
function Counter() { const [count, setCount] = useState(0);
return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}> Click Me </button> </div> ); } ```
**What's happening:**
- `useState(0)` creates state with initial value 0 - `count` is the current value - `setCount` is a function to update the value
How useState Works
```javascript const [value, setValue] = useState(initialValue); ```
- **value** - Current state value - **setValue** - Function to change the value - **initialValue** - Starting value (0, "", true, etc.)
Simple Examples
### Example 1: Toggle Button
```javascript function ToggleButton() { const [isOn, setIsOn] = useState(false);
return ( <button onClick={() => setIsOn(!isOn)}> {isOn ? 'ON' : 'OFF'} </button> ); } ```
### Example 2: Text Input
```javascript function NameInput() { const [name, setName] = useState('');
return ( <div> <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter your name" /> <p>Hello, {name}!</p> </div> ); } ```
### Example 3: Like Button
```javascript function LikeButton() { const [likes, setLikes] = useState(0);
return ( <button onClick={() => setLikes(likes + 1)}> ❤️ {likes} Likes </button> ); } ```
Multiple State Variables
You can have many state variables in one component:
```javascript function UserProfile() { const [name, setName] = useState('John'); const [age, setAge] = useState(25); const [city, setCity] = useState('New York');
return ( <div> <p>Name: {name}</p> <p>Age: {age}</p> <p>City: {city}</p> </div> ); } ```
Updating State with Objects
When state is an object, create a new object when updating:
```javascript function UserForm() { const [user, setUser] = useState({ name: 'Sarah', age: 28 });
const updateName = () => { setUser({ ...user, // Keep old values name: 'Jennifer' // Update name }); };
return ( <div> <p>{user.name}, {user.age} years old</p> <button onClick={updateName}>Change Name</button> </div> ); } ```
The `...user` is called "spread operator" - it copies the old values.
Common Mistakes
### ❌ Don't Modify State Directly
```javascript // Wrong count = count + 1; ```
### ✅ Use setState Function
```javascript // Correct setCount(count + 1); ```
State vs Props
**Props:** - Passed from parent component - Cannot be changed by component - Like function parameters
**State:** - Managed inside component - Can be changed by component - Like variables inside a function
Remember
- State is component's memory - Use `useState` to create state - State changes trigger re-render - Always use setState function to update - Each component has its own state
> Next: Learn React Events - How to handle clicks, typing, and more!