SmartCodingTips

๐ŸŒ Using fetch() in React

The fetch() API is a native JavaScript function used to make HTTP requests. In React, it's commonly used inside the useEffect() hook to load data from an API when a component mounts.


๐Ÿš€ Example: Fetching Data from an API


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

function UsersList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((res) => res.json())
      .then((data) => setUsers(data));
  }, []);

  return (
    <div>
      <h2>Users</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}
  

๐Ÿ“Œ Best Practices

  • Use useEffect() to run fetch on component mount.
  • Always handle loading and error states.
  • Use async/await for cleaner syntax if preferred.

๐Ÿงผ Cleaner Version Using async/await


useEffect(() => {
  const fetchData = async () => {
    try {
      const res = await fetch('https://jsonplaceholder.typicode.com/users');
      const data = await res.json();
      setUsers(data);
    } catch (error) {
      console.error('Failed to fetch users', error);
    }
  };

  fetchData();
}, []);
  

๐Ÿ“‹ Summary

  • fetch() is used to get data from external APIs.
  • Combine with useEffect() for side effects in React.
  • Always manage loading, success, and error states.