Hi, I'm Jacob. Enjoying devFlipCards? Buy me a coffee

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.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz