Sub topic 2
Updating State from Event Handlers
Assume you know JavaScript functions, JSX, React components and props, and the basics of useState. Event handlers are functions that React calls after an interaction. They can update state, cancel browser behavior, and read the event object.
Updating state from handlers
When the next state depends on the previous state, use a functional update. React queues these updates in order.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(c => c + 1);
setCount(c => c + 1);
}
return <button onClick={handleClick}>Count: {count}</button>;
}Each click adds two. Using setCount(count + 1) twice can calculate both updates from the same older value, so the result may increase by only one.
Preventing default browser behavior
Some browser actions have defaults. Submitting a form usually reloads the page. Call event.preventDefault() when React should handle the action instead.
function SearchForm({ onSearch }) {
function handleSubmit(event) {
event.preventDefault();
onSearch(event.currentTarget.elements.query.value);
}
return (
<form onSubmit={handleSubmit}>
<input name="query" />
<button type="submit">Search</button>
</form>
);
}Controlled inputs with `onChange`
A controlled input gets its displayed value from React state. Its onChange handler stores each new value in that state.
import { useState } from 'react';
function NameInput() {
const [name, setName] = useState('');
return (
<label>
Name
<input
value={name}
onChange={event => setName(event.target.value)}
/>
<p>Hello, {name || 'visitor'}</p>
</label>
);
}The value prop and onChange handler work together. If you provide value without updating it, the input appears read-only.
Handling form submission
Put submission logic on the form's onSubmit, rather than only on the button's onClick. This also handles pressing Enter in a field. Use type="button" for buttons that should not submit the form.
Exercise
Why should a form submit handler call preventDefault() before sending data with application code?
Show answer
It prevents the browser's normal page reload, allowing React code to validate or send the data while keeping the current page.