State in React
State is used to manage data that changes within a component. Unlike props, state is mutable and controlled by the component itself.
Using the useState
Hook
-
Import
useState
import { useState } from 'react';
-
Initialize state
const [count, setCount] = useState(0);
-
Update state
setCount(count + 1);
Example of State
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Updating and Managing State
-
Updating State
- State updates are asynchronous. React batches multiple state updates for performance.
- Use the previous state for calculations
setCount((prevCount) => prevCount + 1);
-
Managing Complex State
- For objects or arrays, update using the spread operator
const [user, setUser] = useState({ name: "John", age: 25 }); setUser((prevUser) => ({ ...prevUser, age: 26 }));
-
Conditional Rendering Based on State
function Toggle() { const [isOn, setIsOn] = useState(false); return ( <button onClick={() => setIsOn(!isOn)}> {isOn ? "ON" : "OFF"} </button> ); }
-
State in Forms Manage input fields using state
function Form() { const [name, setName] = useState(""); return ( <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> ); }
Summary
Feature | Props | State |
---|---|---|
Mutability | Immutable (read-only) | Mutable (can be updated) |
Scope | Passed from parent to child | Local to the component |
Use Case | Passing data between components | Managing dynamic, interactive data |
Example | <Child name="John" /> |
const [count, setCount] = useState(0) |
- Props make components reusable by passing dynamic data.
- State manages component-specific data that changes over time.