Handling Side Effects with React's useEffect


React's useEffect hook allows us to handle side effects in functional components. Side effects are actions that occur outside of our component, such as HTTP requests, timers, and manual DOM manipulation.

One common use case is fetching data from an API. Here's a basic example:

import React, { useState, useEffect } from 'react'; function Example() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com') .then(response => response.json()) .then(data => setData(data)); }, []); return data ? <div>{data}</div> : <div>Loading...</div>; }

In the example above, the useEffect hook is used to fetch data from an API once the component is mounted. The empty array [] as the second argument signifies that the effect should only run once after the initial render.

Remember to clean up your effects (like clearing timers or cancelling API requests) to prevent memory leaks. You can do this by returning a function from your effect.

useEffect(() => { const timerID = setInterval(() => tick(), 1000); return function cleanup() { clearInterval(timerID); }; });

In this case, the returned cleanup function will be run before the component is removed from the UI to prevent memory leaks.

Keep experimenting and happy coding! You can find me at @samuellawrentz on X.

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?