Using Effect Hook for Side Effects in React | Javascript
import React, { useState, useEffect } from 'react';
const DataFetcher = () => {
const [data, setData] = useState(null);
useEffect(() => {
// Fetch data from an API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data:', error));
}, []); // Empty dependency array ensures effect runs only once
return (
<div>
{data ? <p>Data: {data}</p> : <p>Loading...</p>}
</div>
);
}
export default DataFetcher;
This code demonstrates a functional React component called `DataFetcher` that fetches data from an API when the component mounts, using the `useState` and `useEffect` hooks. Explanation of the code: 1. The `DataFetcher` component uses the `useState` hook to declare a state variable `data` and a setter function `setData` to manage the fetched data. 2. The `useEffect` hook is used to perform side effects in function components. In this case, `useEffect` is called with a callback function that fetches data from an API endpoint 'https://api.example.com/data' when the component mounts. 3. The `.then()` method is used to handle the response by parsing it to JSON format and updating the `data` state using `setData`. 4. The `.catch()` method is used to handle any errors that occur during the API request. 5. The empty dependency array `[]` ensures that the effect runs only once when the component mounts and not re-runs on subsequent re-renders. 6. In the `return` statement, a conditional rendering is used to display either the fetched data (if it exists) or a 'Loading...' message if data is still being fetched. Overall, this component fetches data from an API when it mounts, updates the UI to display the fetched data, and handles loading and error states effectively.