State and Events 🔋
State captures dynamic data; events are how users change it. Mastering both unlocks interactive React apps.
1) Introducing useState ⚛️
useStatereturns[value, setter].- Setters schedule re-renders with the new value.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(prev => prev + 1)}>+1</button>
</div>
);
}🔄 Always derive the next value from the previous one when updating rapidly (use the functional form).
2) Handling Events 🧠
React normalizes browser events into SyntheticEvents.
function NewsletterSignup() {
function handleSubmit(event) {
event.preventDefault();
console.log("Submitted!");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Subscribe</button>
</form>
);
}- Event props start with
on, e.g.,onClick,onChange. - Always prevent default form submission when handling client-side.
3) Controlled vs Uncontrolled Inputs ✅❌
Controlled input keeps value in React state.
function EmailField() {
const [email, setEmail] = useState("");
return (
<label>
Email
<input
value={email}
onChange={event => setEmail(event.target.value)}
/>
</label>
);
}- ✅ One source of truth, easy validation.
- ❌ More code, but predictable.
Uncontrolled input lets the DOM store the value (use ref).
import { useRef } from "react";
function FilePicker() {
const fileRef = useRef(null);
function handleUpload() {
console.log(fileRef.current.files[0]);
}
return (
<div>
<input type="file" ref={fileRef} />
<button onClick={handleUpload}>Upload</button>
</div>
);
}- ✅ Handy for file inputs or simple uncontrolled forms.
- ❌ Harder to validate and sync.
4) Simple Forms 🧾
- Store each field in state or use a single object.
- Validate on change or submit.
function LoginForm() {
const [form, setForm] = useState({ email: "", password: "" });
function handleChange(event) {
const { name, value } = event.target;
setForm(prev => ({ ...prev, [name]: value }));
}
function handleSubmit(event) {
event.preventDefault();
console.log(form);
}
return (
<form onSubmit={handleSubmit}>
<input name="email" value={form.email} onChange={handleChange} />
<input name="password" value={form.password} onChange={handleChange} />
<button type="submit">Log In</button>
</form>
);
}Key Takeaways ✅
useStateholds data per component and triggers renders when updated.- Event handlers receive SyntheticEvents; prevent default form behavior when needed.
- Controlled inputs keep React as the single source of truth; uncontrolled inputs rely on the DOM.
- Forms combine state, events, and validation into user-friendly flows.
Recap 🔄
State stores dynamic values, events mutate that state, and controlled inputs ensure React remains in charge. Knowing when to control vs leave inputs unmanaged, plus structuring forms with useState, gives you predictable, debuggable interactions.
Last updated on