13. How do you manage asynchronous operations in React components?

Managing asynchronous operations in React components involves using hooks like useEffect to perform tasks such as data fetching, and ensuring proper cleanup of side effects to avoid memory leaks and incorrect state updates.

Example of data fetching with useEffect:

import React, { useState, useEffect } from 'react'; function DataFetchingComponent() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { let isSubscribed = true; async function fetchData() { const response = await fetch('https://api.example.com/data'); const result = await response.json(); if (isSubscribed) { setData(result); setLoading(false); } } fetchData(); return () => { isSubscribed = false; }; }, []); if (loading) { return <div>Loading...</div>; } return ( <div> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }

Ensuring cleanup of side effects: When working with asynchronous operations, it is important to ensure that side effects are cleaned up when the component unmounts to avoid memory leaks and incorrect state updates.

In the example above, a variable isSubscribed is used to check if the component is still mounted before setting the state after the asynchronous operation completes.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.