01 December 2024
State is used to manage data that changes within a component. Unlike props, state is mutable and controlled by the component itself.
useState
HookImport useState
import { useState } from 'react';
Initialize state
const [count, setCount] = useState(0);
Update state
setCount(count + 1);
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Updating State
setCount((prevCount) => prevCount + 1);
Managing Complex State
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)}
/>
);
}
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) |