How to use the useEffect Hook for side effects in React?

To use the useEffect Hook for side effects in React, you first need to import the useEffect Hook from the 'react' library in your functional component.

Here's an example of using the useEffect Hook to fetch data from an API when the component mounts:

import React, { useState, useEffect } from 'react'; function MyComponent() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)) .catch(error => console.error(error)); }, []); return ( <div> {data ? ( <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ) : ( <p>Loading...</p> )} </div> ); } export default MyComponent;

In this example, the useEffect Hook is being used to fetch data from an API when the component mounts. The useEffect Hook takes two arguments: a function that performs the side effect (fetching data in this case) and an optional array of dependencies. In this case, an empty array is passed as the second argument to ensure that the effect is only run once when the component mounts.

It's important to note that the useEffect Hook can also be used for other side effects such as setting up event listeners, subscriptions, or updating the document title. Just make sure to clean up any side effects that might cause memory leaks or other issues, by returning a cleanup function from the useEffect Hook.