React ยท Chapter 6 of 42
State
State is data that a component manages internally and that can change over time. Unlike props, state is private to a component and can be updated, causing React to re-render.
In function components, state is managed with the `useState` hook.
State vs props
Props come from outside and are read-only; state is owned and controlled by the component itself and can change.
Updating state
Calling the state setter function schedules a re-render with the new value. State updates in React are asynchronous and batched.
Example 1 (jsx)
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}Output
Count: 0 (increments on click)Clicking the button updates state and re-renders the component.
Key points
- State is private, mutable data owned by a component.
- useState returns a value and a setter function.
- Calling the setter triggers a re-render.
- State updates may be batched and are asynchronous.
๐ก Note: Never mutate state directly (e.g. `count++`) โ always use the setter function.
