use-multi-fetch-lite
v1.0.8
Published
Lightweight React hook for handling multiple API calls
Downloads
49
Readme
use-multi-fetch-lite ⚡
A lightweight React hook for handling multiple API calls with built-in protection against infinite re-fetching and React StrictMode issues.
Perfect for when React Query feels like overkill.
✨ Features
- Multiple API calls in one hook — Fetch from several endpoints simultaneously
- Sequential fetching — Safe by default, prevents race conditions
- Retry support — Automatically retry failed requests
- 🛑 Auto-protected — Guards against infinite re-fetch loops
- React StrictMode safe — Works flawlessly with double-invocation
- Unified state management — Single loading and error state for all requests
- TypeScript ready — Full type safety included
- Zero dependencies — Lightweight and fast
📦 Installation
npm install use-multi-fetch-liteOr with yarn:
yarn add use-multi-fetch-liteReact 18 & StrictMode
use-multi-fetch-lite is fully compatible with React 18 and StrictMode.
The hook safely handles React's development double-invocation by:
- Preventing stale async updates
- Avoiding state resets during cleanup
- Ensuring only the latest fetch run updates state
🚀 Quick Start
Basic Usage (JavaScript)
import { useMultiFetch } from "use-multi-fetch-lite";
const fetchUsers = () =>
fetch("https://jsonplaceholder.typicode.com/users").then(r => r.json());
const fetchPosts = () =>
fetch("https://jsonplaceholder.typicode.com/posts").then(r => r.json());
export default function App() {
const { data, loading, error } = useMultiFetch({
users: fetchUsers,
posts: fetchPosts,
});
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h2>Users: {data.users?.length ?? 0}</h2>
<h2>Users: {data.users?.length ?? 0}</h2>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}TypeScript Usage
import { useMultiFetch } from "use-multi-fetch-lite";
type User = {
id: number;
name: string;
email: string;
};
type Post = {
id: number;
title: string;
body: string;
};
const fetchUsers = async (): Promise<User[]> => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
return res.json();
};
const fetchPosts = async (): Promise<Post[]> => {
const res = await fetch("https://jsonplaceholder.typicode.com/posts");
return res.json();
};
export default function App() {
const { data, loading, error } = useMultiFetch({
users: fetchUsers,
posts: fetchPosts,
});
// data is fully typed as { users: User[]; posts: Post[] }
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
{data.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}⚙️ Advanced Configuration
With Options
const { data, loading, error } = useMultiFetch(
{
users: fetchUsers,
posts: fetchPosts,
comments: fetchComments,
},
{
retry: 2,
onSuccess: (data) => {
console.log("✅ All requests succeeded:", data);
},
onError: (error) => {
console.error("❌ Request failed:", error);
},
}
);Available Options
| Option | Type | Default | Description |
|-------------|-------------------|---------|------------------------------------------|
| retry | number | 0 | Number of retry attempts per request |
| onSuccess | (data) => void | — | Callback fired when all requests succeed |
| onError | (error) => void | — | Callback fired when any request fails |
📤 Return Values
The hook returns an object with the following properties:
{
data: Record<string, any> // `data` is always an object. Before the first successful fetch, it will be an empty object (`{}`).
loading: boolean; // True while any request is pending
error: Error | null; // First error encountered, if any
}Data Shape
The data object keys match your fetch function keys:
// Input:
useMultiFetch({
users: fetchUsers,
posts: fetchPosts,
})
// Output data:
{
users: User[],
posts: Post[]
}🧠 How It Works
- Sequential execution — Requests run one after another to prevent race conditions
- StrictMode compatible — Handles React 18's double-invocation in development
- Smart caching — Prevents unnecessary re-fetches automatically
- Error handling — Stops on first error and returns it immediately
- Type inference — Automatically infers return types from your fetch functions
💡 When to Use This
Great for:
- Small to medium applications
- Simple data fetching needs
- Learning React hooks
- Projects where you want to avoid heavy dependencies
Consider alternatives when:
- You need advanced caching strategies
- You require background refetching
- You want optimistic updates
- You're building a large-scale application (consider React Query, SWR, or RTK Query)
📝 License
MIT
Found a bug? Open an issue
Have a feature request? Start a discussion
