How to Make GET Request in React: Simple Guide with Example
In React, you can make a GET request using the
fetch API inside the useEffect hook to load data when the component mounts. Use async/await to handle the response and update state with useState.Syntax
To make a GET request in React, use the fetch function inside useEffect. The fetch function takes the URL as a parameter and returns a promise. Use await to wait for the response and then convert it to JSON. Update the component state with the fetched data.
useEffect: Runs code after the component renders.fetch(url): Sends GET request to the URL.await response.json(): Parses the response body as JSON.useState: Stores the fetched data in state.
javascript
import React, { useState, useEffect } from 'react'; function MyComponent() { const [data, setData] = useState(null); useEffect(() => { async function fetchData() { const response = await fetch('https://api.example.com/data'); const json = await response.json(); setData(json); } fetchData(); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; } export default MyComponent;
Example
This example shows a React component that fetches a list of users from a public API when it loads. It displays the users' names or a loading message while waiting.
javascript
import React, { useState, useEffect } from 'react'; function UserList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchUsers() { try { const response = await fetch('https://jsonplaceholder.typicode.com/users'); const data = await response.json(); setUsers(data); } catch (error) { console.error('Error fetching users:', error); } finally { setLoading(false); } } fetchUsers(); }, []); if (loading) return <p>Loading users...</p>; return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); } export default UserList;
Output
<ul><li>Leanne Graham</li><li>Ervin Howell</li><li>Clementine Bauch</li><li>Patricia Lebsack</li><li>Chelsey Dietrich</li><li>Mrs. Dennis Schulist</li><li>Kurtis Weissnat</li><li>Nicholas Runolfsdottir V</li><li>Glenna Reichert</li><li>Clementina DuBuque</li></ul>
Common Pitfalls
Common mistakes when making GET requests in React include:
- Not using
useEffectto avoid repeated requests on every render. - Forgetting to handle errors, which can cause the app to crash or hang.
- Not setting the dependency array in
useEffect, causing infinite loops. - Trying to make the
useEffectcallback async directly, which is not allowed.
Always wrap async calls inside a function inside useEffect.
javascript
/* Wrong way: async directly in useEffect callback causes warning */ useEffect(async () => { const response = await fetch(url); const data = await response.json(); setData(data); }, []); /* Right way: define async function inside useEffect and call it */ useEffect(() => { async function fetchData() { const response = await fetch(url); const data = await response.json(); setData(data); } fetchData(); }, []);
Quick Reference
Tips for making GET requests in React:
- Use
fetchor libraries like Axios for HTTP requests. - Always perform requests inside
useEffectto control when they run. - Handle loading and error states for better user experience.
- Keep the dependency array empty
[]to run the request only once on mount.
Key Takeaways
Use the fetch API inside useEffect to make GET requests when the component loads.
Wrap async calls inside a function inside useEffect; do not make the useEffect callback async.
Handle loading and error states to improve user experience.
Keep the useEffect dependency array empty to avoid repeated requests.
Update component state with useState to display fetched data.