useeffect in javascript

The useEffect hook in React is a way to use lifecycle methods in functional components. It runs after every render by default, but can also be set to run only when certain props or state values change.

Here is an example of how to use useEffect to fetch data from an API:

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

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

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

  return (
    <div>
      {data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}
459 chars
23 lines

In this example, useEffect is called with a function that fetches data from an API when the component mounts (or when [] changes). The fetched data is stored in data using the useState hook. The component renders the fetched data in a list.

gistlibby LogSnag