BP213: Use the useEffect hook to handle side effects

Use the useEffect hook to handle side effects. Side effects are any actions that are not directly related to rendering a component, such as fetching data from an API or updating the document title. The useEffect hook allows you to perform these side effects in a declarative way, without cluttering your component's code with imperative logic.

The useEffect hook takes two arguments: a function that performs the side effect, and an array of dependencies that determine when the effect should be re-run. The function is called after the component is rendered for the first time, and then after every subsequent re-render if any of the dependencies have changed. If you pass an empty array as the second argument, the effect will only be run once, after the initial render.

Here's an example of using the useEffect hook to fetch data from an API:

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <ul>
      {data.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

In this example, the useEffect hook is used to fetch data from an API and update the component's state with the result. The empty array passed as the second argument ensures that the effect is only run once, after the initial render. If you wanted to re-fetch the data whenever a prop or state value changes, you could include those values in the dependency array.

Comments

No Comments Yet.
Be the first to tell us what you think.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play