# Lesson 7 - Creating Custom Hooks - useBooks and api-client

## 1. The Concept of Custom Hooks in React

<figure><img src="/files/sA85pM7Fpe5Etyg52oab" alt="" width="375"><figcaption></figcaption></figure>

### **What are Custom Hooks?**

* **Reusable logic functions:** Custom hooks are JavaScript functions that encapsulate reusable logic for React components. They allow you to extract common logic from multiple components and reuse it, promoting modularity and code reuse.
* **Start with "use":** Custom hook functions should be named with the prefix "use" to signify that they are custom hooks.
* **Use built-in hooks:** Custom hooks can use other built-in React hooks like `useState`, `useEffect`, and `useContext`.

### **When to Use Custom Hooks**

Custom hooks are particularly useful when you have logic that needs to be shared across multiple components or when you want to organize your code into smaller, more manageable units. Here are some common scenarios where custom hooks can be beneficial:

* **Fetching data:** You can create a custom hook to handle fetching data from an API, caching it, and managing loading states.
* **Form management:** You can create a custom hook to handle form validation, input handling, and resetting form states.
* **State management:** You can create custom hooks to manage local state that is specific to a component or group of components.
* **Authentication:** You can create a custom hook to handle user authentication and manage user session data.
* **Caching:** You can create a custom hook to cache data in memory or local storage to improve performance.

### **Benefits of Using Custom Hooks**

* **Improved code readability and maintainability:** Custom hooks help to break down complex logic into smaller, more manageable units, making your code easier to read and understand.
* **Increased reusability:** Custom hooks allow you to reuse logic across multiple components, reducing code duplication and improving code efficiency.
* **Better modularity:** Custom hooks promote modularity by encapsulating specific functionalities, making it easier to isolate and test individual components.
* **Enhanced readability:** Custom hooks can help to improve the readability of your code by giving descriptive names to common logic patterns.

### **How to Create a Custom Hook**

To create a custom hook, simply define a JavaScript function that starts with the "use" prefix and follows the rules for React hooks. Inside the function, you can use other built-in hooks and define the logic that you want to encapsulate. Finally, you can return any values that you want to make available to the component that uses the custom hook.

### **Example:**

Here's a simple example of a custom hook that fetches data from an API:

J<mark style="color:green;">avaScript Code for Custom Hook - useFetch.js</mark>

```javascript
import { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch(url)
      .then(response => response.json())
      .then(data => {
        setData(data);
        setLoading(false);
      })
      .catch(error => {
        setError(error);
        setLoading(false);
      });
  }, [url]);

  return { data, loading, error };
}
```

You can then use this custom hook in any React component that needs to fetch data from the specified URL.

### **Conclusion**

Custom hooks are a powerful feature in React that allow you to write reusable, modular, and maintainable code. They can be used to encapsulate common logic patterns, improve code readability, and enhance the overall development experience. By leveraging custom hooks effectively, you can create more efficient and scalable React applications.

## 2. Setup the api-client File and Implementing fetchBooks

To implement a custom hook (`useBooks.js`) and refactor the `AppBookShelf.jsx` component for better modularity, follow these steps:

### **Step 1. Create the `services` Folder**

* Inside the `src` folder, create a new folder named `services`.

***

### **Step 2. Implement `api-client.js`**

Create a file named `api-client.js` in the `services` folder.

**Code for `api-client.js`**

```javascript
const BASE_URL = 'https://www.googleapis.com/books/v1';

export const fetchBooks = async (query) => {
  try {
    const response = await fetch(`${BASE_URL}/volumes?q=${query}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data.items || [];
  } catch (error) {
    console.error('Error fetching books:', error);
    throw error; // Re-throw the error for the caller to handle
  }
};
```

**Explanation:**

1. **`BASE_URL`**:
   * Stores the base URL for the Google Books API.
2. **`fetchBooks` Function**:
   * Accepts a `query` parameter.
   * Makes an API request using `fetch`.
   * Returns an array of books or an empty array if none are found.
   * Logs errors and re-throws them for the caller to handle.

***

### **Step 3. Implement `useBooks.js`**

Create a file named `useBooks.js` in the `services` folder.

**Code for `useBooks.js`**

```javascript
import { useState, useEffect } from 'react';
import { fetchBooks } from './api-client';

const useBooks = (query) => {
  const [books, setBooks] = useState([]);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchBookData = async () => {
      setLoading(true);
      setError(null);
      try {
        const bookData = await fetchBooks(query);
        setBooks(bookData);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    if (query) {
      fetchBookData();
    }
  }, [query]);

  return { books, error, loading };
};

export default useBooks;
```

**Explanation:**

1. **State Variables**:
   * `books`: Holds the fetched book data.
   * `error`: Stores error messages if the fetch fails.
   * `loading`: Indicates whether the data is currently being fetched.
2. **`useEffect` Hook**:
   * Executes `fetchBookData` whenever the `query` changes.
3. **Return Value**:
   * Exposes `books`, `error`, and `loading` to the parent component.

***

### **Step 4. Refactor `AppBookShelf.jsx`**

Modify `AppBookShelf.jsx` to use the `useBooks` hook.

**Updated Code for `AppBookShelf.jsx`**

```jsx
import React, { useState, useEffect } from 'react';
import NavBar from './components/NavBar';
import BookList from './components/BookList';
import Footer from './components/Footer';
import useBooks from './services/useBooks';
import 'bootstrap/dist/css/bootstrap.min.css';
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'


const AppBookShelf = () => {
  const [query, setQuery] = useState('react'); // Default query for API
  const { books, error, loading } = useBooks(query); // Use custom hook

  // Handle query updates from child components
  const handleSearch = (newQuery) => {
    setQuery(newQuery);
  };

  return (
    <div className="container mt-5">
      <NavBar query={query} onSearch={handleSearch} />

      {loading ? (
        <p className="text-center">Loading...</p>
      ) : error ? (
        <p className="text-center text-danger">Error: {error}</p>
      ) : (
        <BookListUpdates books={books} query={query} />
      )}

      <Footer />
    </div>
  );
};

export default AppBookShelf;
```

**Explanation:**

1. **Import `useBooks`**:
   * Fetches book data using the custom hook.
2. **State Handling**:
   * Displays loading, error, or book list based on the hook's output.
3. **Separation of Concerns**:
   * The `fetchBooks` logic is moved out of the component, improving maintainability.

***

### **Step 5. Benefits of This Refactor**

1. **Reusability**:
   * The `useBooks` hook can be reused in other components or projects.
2. **Modularity**:
   * `api-client.js` separates the API interaction from the application logic.
3. **Simplified Parent Component**:
   * `AppBookShelf` focuses on rendering UI and handling user interaction.

This completes the implementation of a modular architecture using a custom hook and API client.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://reactjs.koida.tech/restful-apis-build-a-booksearch-app-ver-2.0/lesson-7-creating-custom-hooks-usebooks-and-api-client.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
