Home >Web Front-end >JS Tutorial >Using useEffect for Fetching Data in React
In React, the useEffect hook is commonly used for performing side effects in functional components. Fetching data from an API or server is one of the most common side effects, and useEffect makes it easy to manage data fetching in your components. Below is a detailed explanation and example of how to use useEffect to fetch data in a React functional component.
To fetch data with useEffect, you generally use the following pattern:
Here’s an example that demonstrates how to fetch data from an API using useEffect and useState:
import React, { useState, useEffect } from 'react'; const DataFetchingComponent = () => { // State variables to store data, loading status, and errors const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // Using useEffect to fetch data useEffect(() => { // Define the function for fetching data const fetchData = async () => { try { // Start by setting loading state to true setLoading(true); // Make the fetch request const response = await fetch('https://api.example.com/data'); // Check if the response is ok (status code 200-299) if (!response.ok) { throw new Error('Network response was not ok'); } // Parse the JSON data const result = await response.json(); // Update the state with the fetched data setData(result); } catch (error) { // Handle errors and set the error state setError(error.message); } finally { // Set loading to false once the request is complete setLoading(false); } }; // Call the fetchData function fetchData(); }, []); // Empty dependency array means this effect runs once when the component mounts // Conditionally render the UI based on loading, error, and data if (loading) { return <div>Loading...</div>; } if (error) { return <div>Error: {error}</div>; } return ( <div> <h1>Data Fetching Example</h1> <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); }; export default DataFetchingComponent;
State Variables:
useEffect Hook:
Loading and Error Handling:
Async Function in useEffect:
Empty Dependency Array ([]):
Error Handling:
State Management:
Sometimes, you may not want to fetch data when the component mounts but rather based on user interaction, like clicking a button. In this case, you can trigger useEffect by updating a state variable from an event handler.
import React, { useState, useEffect } from 'react'; const DataFetchingComponent = () => { // State variables to store data, loading status, and errors const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // Using useEffect to fetch data useEffect(() => { // Define the function for fetching data const fetchData = async () => { try { // Start by setting loading state to true setLoading(true); // Make the fetch request const response = await fetch('https://api.example.com/data'); // Check if the response is ok (status code 200-299) if (!response.ok) { throw new Error('Network response was not ok'); } // Parse the JSON data const result = await response.json(); // Update the state with the fetched data setData(result); } catch (error) { // Handle errors and set the error state setError(error.message); } finally { // Set loading to false once the request is complete setLoading(false); } }; // Call the fetchData function fetchData(); }, []); // Empty dependency array means this effect runs once when the component mounts // Conditionally render the UI based on loading, error, and data if (loading) { return <div>Loading...</div>; } if (error) { return <div>Error: {error}</div>; } return ( <div> <h1>Data Fetching Example</h1> <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); }; export default DataFetchingComponent;
In this example:
Using useEffect for fetching data in React is an efficient and clean way to manage side effects. By combining it with useState, you can manage data fetching, loading states, and error handling in your functional components. Always remember to handle errors and edge cases to ensure your app provides a good user experience.
The above is the detailed content of Using useEffect for Fetching Data in React. For more information, please follow other related articles on the PHP Chinese website!