Lesson 7 - Creating Custom Hooks - useBooks and api-client
Last updated
Last updated
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
.
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.
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.
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.
Here's a simple example of a custom hook that fetches data from an API:
JavaScript Code for Custom Hook - useFetch.js
You can then use this custom hook in any React component that needs to fetch data from the specified URL.
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.
To implement a custom hook (useBooks.js
) and refactor the AppBookShelf.jsx
component for better modularity, follow these steps:
services
FolderInside the src
folder, create a new folder named services
.
api-client.js
Create a file named api-client.js
in the services
folder.
Code for api-client.js
Explanation:
BASE_URL
:
Stores the base URL for the Google Books API.
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.
useBooks.js
Create a file named useBooks.js
in the services
folder.
Code for useBooks.js
Explanation:
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.
useEffect
Hook:
Executes fetchBookData
whenever the query
changes.
Return Value:
Exposes books
, error
, and loading
to the parent component.
AppBookShelf.jsx
Modify AppBookShelf.jsx
to use the useBooks
hook.
Updated Code for AppBookShelf.jsx
Explanation:
Import useBooks
:
Fetches book data using the custom hook.
State Handling:
Displays loading, error, or book list based on the hook's output.
Separation of Concerns:
The fetchBooks
logic is moved out of the component, improving maintainability.
Reusability:
The useBooks
hook can be reused in other components or projects.
Modularity:
api-client.js
separates the API interaction from the application logic.
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.