You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
While props let you pass data down, state lets a component remember information and change it over time. Combined with event handlers, state makes your UI interactive. This lesson covers useState, events, forms, controlled inputs, lifting state up, and immutable updates.
State is data that a component owns and can change over time. When state changes, React automatically re-renders the component.
| Props | State |
|---|---|
| Passed from parent | Owned by the component |
| Read-only | Can be updated |
| Triggers re-render when changed | Triggers re-render when changed |
The useState hook lets you add state to a function component:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
const [value, setValue] = useState(initialValue);
│ │ │
│ │ └─ Initial value (used on first render only)
│ └─ Function to update the value
└─ Current value
function UserForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [age, setAge] = useState(0);
return (
<form>
<input value={name} onChange={(e) => setName(e.target.value)} />
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<input
type="number"
value={age}
onChange={(e) => setAge(Number(e.target.value))}
/>
</form>
);
}
React events use camelCase naming and pass a function reference (not a function call):
// Correct — pass a function reference
<button onClick={handleClick}>Click me</button>
// Wrong — this calls the function immediately on render
<button onClick={handleClick()}>Click me</button>
| Event | HTML Element | Description |
|---|---|---|
onClick | buttons, links | User clicks the element |
onChange | inputs, selects | Value changes |
onSubmit | forms | Form is submitted |
onKeyDown | inputs | Key is pressed |
onFocus | inputs | Element gains focus |
onBlur | inputs | Element loses focus |
function ItemList() {
const items = ["Apple", "Banana", "Cherry"];
const handleClick = (item: string) => {
alert(`You clicked: ${item}`);
};
return (
<ul>
{items.map((item) => (
<li key={item}>
<button onClick={() => handleClick(item)}>{item}</button>
</li>
))}
</ul>
);
}
A controlled input is an input whose value is driven by React state:
function SearchBox() {
const [query, setQuery] = useState("");
return (
<div>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
<p>Searching for: {query}</p>
</div>
);
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.