Using State and Effect Hooks
When working with APIs in React, it's common to manage the API data using state
and effect
hooks. State hooks allow us to store and update the API data in our components, while the effect hook helps us fetch the data and handle any side effects.
Here's an example of how to use state and effect hooks to manage API data in React:
1import React, { useState, useEffect } from 'react';
2
3function MyComponent() {
4 const [data, setData] = useState(null);
5
6 useEffect(() => {
7 fetchData();
8 }, []);
9
10 const fetchData = async () => {
11 try {
12 const response = await fetch('https://api.example.com/data');
13 const data = await response.json();
14 setData(data);
15 } catch (error) {
16 console.error(error);
17 }
18 };
19
20 return (
21 <div>
22 {data ? (
23 <div>{/* Render the data here */}</div>
24 ) : (
25 <div>Loading...</div>
26 )}
27 </div>
28 );
29}
30
31export default MyComponent;
In this example, we define a component MyComponent
that uses the state hook useState
to store the API data. Initially, the data is set to null
.
We also use the effect hook useEffect
with an empty dependency array ([]
) to fetch the data once when the component mounts. The fetchData
function is defined as an async
function that makes an API request using the fetch
function.
Once the data is obtained, it is set using the setData
function provided by the state hook. The component's render function conditionally renders the data or a loading message based on the state of the data.
By using state and effect hooks, we can easily manage API data in our React components and update the UI accordingly.
xxxxxxxxxx
export default MyComponent;
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
} catch (error) {
console.error(error);
}
};
return (
<div>
{data ? (
<div>{/* Render the data here */}</div>
) : (
<div>Loading</div>
)}
</div>
);
}