Event Handlers with Async Operations
You'll learn: How to handle asynchronous logic like fetch calls directly inside event handlers using async/await, without reaching for useEffect.
The Core Idea
When a user clicks a button to fetch data, submit a form, or trigger any async action, that logic belongs directly in the event handler—not in a useEffect that watches for state changes. Event handlers are the perfect place for async operations because they run exactly when the user takes action.
The Pattern
async function handleClick() {
try {
const response = await fetch('/api/data');
const data = await response.json();
setData(data);
} catch (error) {
setError(error.message);
}
}
return <button onClick={handleClick}>Load Data</button>;
Notice the async keyword right on the handler function. This lets you use await to pause for the fetch to complete, then update state with the result.
Why Not useEffect?
The mistake many beginners make is watching a "trigger" state variable in an effect:
// ❌ Don't do this
useEffect(() => {
if (shouldFetch) {
fetch('/api/data').then(/* ... */);
}
}, [shouldFetch]);
This creates unnecessary indirection. The user clicked a button—handle it right there in the click handler.
Think of It Like Real Life
When someone rings your doorbell, you answer it immediately. You don't set a flag saying "doorbell was rung" and then check that flag every few seconds to decide whether to answer.
Key Takeaway: Async logic triggered by user actions belongs in event handlers with async/await, not in useEffect watching state changes.