React Hooks Custom hooks

Custom hooks are functions in React that use one or more built-in hooks to encapsulate and reuse logic across multiple components. Custom hooks allow you to extract common patterns and behaviors from your components and share them across your application.

Here’s an example of how to create a custom hook that fetches data from an API:

jsx
import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    async function fetchData() {
      setIsLoading(true);
      const response = await fetch(url);
      const data = await response.json();
      setData(data);
      setIsLoading(false);
    }
    fetchData();
  }, [url]);

  return { data, isLoading };
}

function DataFetcher() {
  const { data, isLoading } = useFetch("https://example.com/data");

  if (isLoading) {
    return 

Loading...

; } return

Data: {data}

; }

In this example, we’re defining a custom hook called `useFetch` that uses `useState` and `useEffect` to fetch data from an API and manage the loading state. We’re also defining a `DataFetcher` component that uses `useFetch` to fetch data and render the result.

The `useFetch` function takes a `url` argument and returns an object with two properties: `data` and `isLoading`. The `data` property contains the fetched data, and the `isLoading` property is a boolean that indicates whether the data is currently being loaded.

By using a custom hook, we can reuse the data fetching logic across multiple components without having to duplicate the code. We can also customize the behavior of the hook by passing different arguments, such as the API endpoint or the polling interval.

Overall, custom hooks are a powerful tool in React that allows you to encapsulate and reuse logic across multiple components. By using custom hooks, you can simplify your code, improve reusability and modularity, and make your application more maintainable and scalable.