logo

Fetch Data with useEffect

A React component that fetches data from an API using useEffect.

8 Stars

Code

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

const FetchData = () => {
  const [data, setData] = useState(null);

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

  return (
    <div>
      {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : 'Loading...'}
    </div>
  );
};

export default FetchData;

Explanation

This component uses the useEffect hook to fetch data from an API when the component mounts. It stores the fetched data in a state variable using the useState hook and displays it in a preformatted text element.