useState Hook
-
This lesson introduces the useState Hook and explains how to manage and update state in React functional components.
The useState hook is used to manage state in functional components.
Syntax:
const [state, setState] = useState(initialValue);
State Initialization
State can be initialized with:
Number
String
Boolean
Array
Object
Example:
const [count, setCount] = useState(0);
Initial value is used only once.
Updating State with Previous Values
When new state depends on old state, use callback syntax.
Example:
setCount(prevCount => prevCount + 1);
This ensures correct updates.
Multiple State Variables
Multiple states can be used in one component.
Example:
const [name, setName] = useState("");
const [age, setAge] = useState(0);
This keeps state logic clean.