How to Use Async Await in React: Simple Guide with Examples
In React, use
async functions inside event handlers or effects to handle asynchronous tasks. Use await to pause execution until a promise resolves, making your code easier to read and manage.Syntax
Use async before a function to mark it as asynchronous. Inside it, use await before a promise to wait for its result without blocking the whole app.
Example parts:
async function fetchData() {}: declares an async function.const result = await fetch(url): waits for the fetch to complete.
javascript
async function fetchData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; }
Example
This example shows a React functional component that fetches user data when a button is clicked. It uses async and await inside the click handler to wait for the data before updating the state.
javascript
import React, { useState } from 'react'; export default function UserFetcher() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); async function handleClick() { setLoading(true); setError(null); try { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); if (!response.ok) throw new Error('Network error'); const data = await response.json(); setUser(data); } catch (err) { setError(err.message); } finally { setLoading(false); } } return ( <div> <button onClick={handleClick} disabled={loading} aria-label="Fetch user data"> {loading ? 'Loading...' : 'Fetch User'} </button> {error && <p role="alert" style={{color: 'red'}}>{error}</p>} {user && ( <div> <h2>{user.name}</h2> <p>Email: {user.email}</p> <p>Phone: {user.phone}</p> </div> )} </div> ); }
Output
When the button is clicked, it shows 'Loading...' then displays user info: name, email, and phone.
Common Pitfalls
Common mistakes include:
- Making the component function itself
async(React does not support this). - Not handling errors with
try/catch, causing silent failures. - Forgetting to update loading state, confusing users.
- Calling
awaitoutside anasyncfunction.
javascript
/* Wrong: async component function (do not do this) */ // async function MyComponent() { // const data = await fetchData(); // React will not handle this properly // return <div>{data}</div>; // } /* Right: async function inside component */ function MyComponent() { async function loadData() { const data = await fetchData(); // use data } // call loadData on event or effect return <div>Content</div>; }
Quick Reference
Remember these tips when using async/await in React:
- Use
asynconly on functions, not on the main component function. - Wrap
awaitcalls intry/catchto handle errors. - Update loading and error states to keep UI responsive.
- Use async functions inside event handlers or
useEffectcallbacks.
Key Takeaways
Use async functions inside event handlers or effects, not on the component itself.
Always use await to pause for promises and try/catch to handle errors.
Update loading and error states to improve user experience.
Avoid calling await outside async functions to prevent errors.
Async/await makes asynchronous React code easier to read and maintain.