logo

Fetching Data with useEffect

A component fetching data from an API using React's useEffect and useState hooks.

24 Stars

Code

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>;

Explanation

This code defines a component that fetches data from an API using React's useEffect and useState hooks. It initializes a data state variable to null and uses useEffect to fetch data when the component mounts. Once the data is fetched, it updates the state with the fetched data. The component conditionally renders the fetched data or a loading message.