API Integration with Custom Hooks
1. Introduction to Custom Hooks
Custom Hooks are JavaScript functions that allow us to reuse stateful logic between React components. They help us organize repeated logic and keep our components clean and readable.
When multiple components need to fetch API data, we can create
a custom hook such as useFetch() and reuse it
wherever required.
use, such as useFetch. Hooks must be
called at the top level of React components or other custom Hooks.
2. Why Use Custom Hooks?
- Reuse API-fetching logic across components.
- Reduce duplicate code.
- Keep components simple and readable.
- Manage loading, data and error states in one place.
- Make application logic easier to maintain and test.
Displays users
Displays posts
The same fetching logic can be reused with different API URLs.
3. Creating a Custom Fetch Hook
First, create a file named useFetch.js inside
the src/hooks folder. This Hook will manage
the API response, loading status and errors.
import { useEffect, useState } from "react";
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function fetchData() {
try {
setLoading(true);
setError("");
setData(null);
const response = await fetch(url, {
signal: controller.signal
});
if (!response.ok) {
throw new Error(
`Request failed: ${response.status}`
);
}
const result = await response.json();
setData(result);
} catch (err) {
if (err.name !== "AbortError") {
setError(
err instanceof Error
? err.message
: "Something went wrong."
);
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchData();
return () => {
controller.abort();
};
}, [url]);
return { data, loading, error };
}
export default useFetch;
4. Understanding the Custom Hook
| Code | Purpose |
|---|---|
useState() |
Stores API data, loading status and errors. |
useEffect() |
Starts the request when the URL changes. |
fetch(url) |
Sends the HTTP request to the API. |
response.ok |
Checks whether the HTTP response indicates success. |
AbortController |
Allows the request to be cancelled during cleanup. |
return { data, loading, error } |
Makes the Hook's state available to its component. |
5. Using the Custom Hook in a Component
Now create a component named Users.jsx.
Import useFetch and pass the users API URL.
The component can then display loading, error or data states.
import useFetch from "../hooks/useFetch";
function Users() {
const {
data: users,
loading,
error
} = useFetch(
"https://jsonplaceholder.typicode.com/users"
);
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return (
<p role="alert">
Unable to load users: {error}
</p>
);
}
if (!Array.isArray(users) || users.length === 0) {
return <p>No users found.</p>;
}
return (
<div>
<h2>User List</h2>
<ul>
{users.map((user) => (
<li key={user.id}>
<strong>{user.name}</strong>
{" - "}
{user.email}
</li>
))}
</ul>
</div>
);
}
export default Users;
6. Reusing the Same Hook for Posts
We do not need to write the same fetching logic again.
We can reuse useFetch() with a different URL
to retrieve posts.
import useFetch from "../hooks/useFetch";
function Posts() {
const {
data: posts,
loading,
error
} = useFetch(
"https://jsonplaceholder.typicode.com/posts"
);
if (loading) {
return <p>Loading posts...</p>;
}
if (error) {
return (
<p role="alert">
Unable to load posts: {error}
</p>
);
}
if (!Array.isArray(posts) || posts.length === 0) {
return <p>No posts found.</p>;
}
return (
<div>
<h2>Posts</h2>
{posts.slice(0, 5).map((post) => (
<article key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</article>
))}
</div>
);
}
export default Posts;
useFetch() gets its own Hook state. The fetching
logic is reused, but the state is not automatically shared
between components.
7. Displaying Components in App.jsx
Import both components into App.jsx to display
the users and posts on the same page.
import Users from "./components/Users";
import Posts from "./components/Posts";
function App() {
return (
<main>
<h1>React API Integration</h1>
<section>
<Users />
</section>
<hr />
<section>
<Posts />
</section>
</main>
);
}
export default App;
8. Expected Output
React API Integration
User List
Leanne Graham - Sincere@example.com
Ervin Howell - Shanna@example.com
...more users
Posts
sunt aut facere repellat provident occaecati...
quia et suscipit suscipit recusandae consequuntur expedita...
...more posts
The displayed values come from the testing API. Actual data appears when the application runs and the requests succeed.
9. Best Practices
- Start custom Hook names with
use. - Keep the Hook focused on reusable logic.
- Include reactive dependencies such as the API URL in the dependency array.
- Handle loading, errors and empty data states.
- Cancel obsolete requests when appropriate.
- Do not call Hooks conditionally or inside loops.
- Use separate Hooks or a data-fetching library when more advanced caching and request coordination are required.
10. Practice Tasks
- Create a custom Hook named
useFetch.js. - Fetch users and display their names and email addresses.
- Reuse the same Hook to fetch posts.
- Display loading and error messages.
- Test the error state using an invalid API URL.
- Modify the URL and observe how the Hook fetches new data.
- Add a third component that fetches comments using the same Hook.
Summary
Custom Hooks allow React developers to reuse API-fetching logic across multiple components. By creating a useFetch Hook with useState, useEffect, loading states, error handling and request cleanup, we can build cleaner, reusable and maintainable React applications.