πŸ”ŒData Handling and Side Effects

Handle asynchronous data, API calls, caching, and complex interactions with grace.

🌐 Working with APIs

Working with APIs is a fundamental skill in modern web development. APIs allow your React applications to interact with external data sources, enabling you to create dynamic and interactive user experiences.

βœ… Making API Requests with fetch

The fetch API is a built-in JavaScript method for making HTTP requests. It's a modern alternative to the older XMLHttpRequest object.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
  • Use .then() to handle the response asynchronously.
  • Parse JSON responses with response.json().
  • Handle errors with .catch().

πŸ’‘ Using Axios for API Requests

While fetch is built into JavaScript, axios provides additional features like error handling and request cancellation.

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));
  • Axios supports GET, POST, PUT, DELETE methods.
  • Use axios.CancelToken to cancel pending requests.
  • Axios throws errors by default for non-200 responses.

βœ… Handling Loading and Error States

Good user experiences require proper handling of loading and error states. Use state management to track the status of API requests.

const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [data, setData] = useState([]);

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    setLoading(false);
    setData(data);
  })
  .catch(error => {
    setLoading(false);
    setError(error);
  });
  • Use loading state to show spinners or loading messages.
  • Display error messages when requests fail.
  • Reset loading and error states on new requests.

πŸ’‘ Working with RESTful APIs

REST (Representational State Transfer) is a popular architectural style for designing networked applications. It uses standard HTTP methods to perform operations on resources.

  • GET: Retrieve data.
  • POST: Create new resources.
  • PUT: Update existing resources.
  • DELETE: Remove resources.

βœ… Introduction to GraphQL

GraphQL is an alternative to REST that allows clients to request exactly the data they need. It's particularly useful for complex applications with many interrelated resources.

const query = `
  {
    user(id: 1) {
      name
      email
      posts {
        title
        content
      }
    }
  }`;
  • GraphQL reduces over-fetching and under-fetching issues.
  • Use Apollo Client or Relay to work with GraphQL in React.
  • Learn more about GraphQL at https://graphql.org/.

πŸ’‘ Common API Patterns for Reusable Logic

Reusable data-fetching logic can save time and reduce code duplication. Consider creating custom hooks or utility functions.

const useData = (url) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [data, setData] = useState([]);

  useEffect(() => {
    const controller = new AbortController();
    
    axios.get(url, { signal: controller.signal })
      .then(response => {
        setLoading(false);
        setData(response.data);
      })
      .catch(error => {
        setLoading(false);
        setError(error);
      });

    return () => controller.abort();
  }, [url]);

  return { loading, error, data };
};
  • Use useEffect to manage side effects.
  • Implement AbortController for cleanup.
  • Create reusable hooks for common API operations.

πŸ” Data Fetching Libraries

Welcome to the chapter on Data Fetching Libraries! Modern web development often requires fetching and managing data asynchronously. While React provides built-in hooks like useEffect, handling data fetching efficiently can be challenging. That's where libraries like React Query and SWR come into play, offering powerful solutions for managing asynchronous state, caching, and synchronization.

πŸ’‘ Why Use Data Fetching Libraries?

  • Simplify complex data fetching workflows by handling loading states, errors, and caching out of the box.
  • Improve performance with built-in caching strategies and stale-while-revalidate patterns.
  • Enhance user experience with features like optimistic updates, pagination, and auto-refetching.

πŸ’‘ Introduction to React Query

React Query is a popular library for managing server state in React applications. It provides a simple yet powerful API for fetching, caching, and synchronizing data. Key features include:

  • Stale-while-revalidate: Show cached data while fetching fresh data.
  • Optimistic updates: Preview changes locally before sending them to the server.
  • Pagination support: Load more data as users scroll or navigate.
  • Global state management: Query, mutate, and manage all data from a single source of truth.

πŸ’‘ Getting Started with React Query

// Install dependencies
npm install react-query @tanstack/react-query-devtools

// Example usage
import { useQuery } from '@tanstack/react-query';

function UsersList() {
  const { data, error, isLoading } = useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const response = await fetch('https://api.example.com/users');
      return response.json();
    },
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error!</div>;

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

πŸ’‘ Introduction to SWR

SWR (Server-Waiting-Response) is another lightweight and flexible library for data fetching in React. It focuses on providing a simple API while offering powerful features like revalidation, pagination, and deduping.

πŸ’‘ Key Features of SWR

  • Stale-while-revalidate: Show cached data while fetching fresh data.
  • Infinite scrolling: Load more content as users interact with the UI.
  • Error boundaries: Handle errors and recover gracefully.
  • Revalidation strategies: Control when and how data is revalidated.
// Install dependencies
npm install swr

// Example usage
import useSWR from 'swr';

function UsersList() {
  const { data, error } = useSWR('https://api.example.com/users');

  if (error) return <div>Error!</div>;
  if (!data) return <div>Loading...</div>;

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

πŸ’‘ Comparison: React Query vs SWR

Both libraries are excellent choices for data fetching in React, but they differ in their approach and features:

  • React Query provides a more opinionated approach with built-in support for complex scenarios like mutations, optimistic updates, and global state management.
  • SWR offers a simpler API that's easier to get started with, making it ideal for smaller applications or specific use cases.

πŸ’‘ Best Practices for Data Fetching

To maximize the benefits of data fetching libraries, follow these best practices:

  • Use stale-while-revalidate to show cached data immediately while fetching fresh updates.
  • Implement pagination for large datasets to avoid loading too much data at once.
  • Optimize caching strategies based on your application's needs and API constraints.
  • Handle errors gracefully with proper error boundaries and recovery mechanisms.

❌ Common Mistakes to Avoid

  • Don't fetch data unnecessarily - use built-in features like deduping and caching to avoid redundant requests.
  • Avoid over-fetching - load only the data your users need at that moment.
  • Don't ignore error handling - always provide a fallback UI when data fetching fails.

πŸ’‘ Real-World Applications

Both React Query and SWR are widely used in production applications. They're especially useful in scenarios like:

  • Building real-time dashboards with auto-refreshing data.
  • Implementing infinite scrolling for social media feeds.
  • Managing complex forms with optimistic updates and mutations.

Quiz

Question 1 of 10

Which method is used to make asynchronous requests in JavaScript?

  • fetch
  • axios
  • XMLHttpRequest
  • All of the above