Managing API calls and shared data in React doesn't have to be a hassle. Dolab simplifies this process with a clean, reusable hook powered by Zustand. It's lightweight, fast, and designed for modern frontend development.
๐ง โDolabโ is the Arabic word for "Drawer" โ and like a drawer, it stores, fetches, and shares your data neatly. ๐ง
๐ Why Use Dolab?
- โ Minimal API surface
- ๐ Auto-refetch with dependency array
- ๐ฆ Shared data store across components
- โณ Optional cache expiration (lifetime)
- ๐ก TypeScript-first design
- โก Built on Zustand (no context, no hassle)
๐ฅ Installation
npm install dolab
๐ง Basic Usage Example
import { SetDolabData, useDolab } from "dolab";
type Todo = { userId: number; id: number; title: string; completed: boolean };
const fetch = async (setData: SetDolabData<Todo[]>) => {
const res = await fetch("https://jsonplaceholder.typicode.com/todos");
setData(await res.json());
};
export default function Todos() {
const { data: todos, loading, triggerRefetch } = useDolab<Todo[]>({
id: "todos", fetch,
});
if (!todos) return (
<button onClick={triggerRefetch}>
{loading ? "Loading..." : "Load Todos"}
</button>
);
return (
<ul>{todos.map(todo => <li key={todo.id}>{todo.title}</li>)}</ul>
);
}
๐ง Note: The data is not just fetched and displayed โ itโs also persisted inside Dolabโs internal store, powered by Zustand. This means you can reuse the same data anywhere across your application without triggering another API call.
To access this stored data in other components, simply use the
useDolabData
hook and pass in the sameid
used earlier ("todos"
in this case):const {data : todos}= useDolabData<Todo[]>({ id: "todos" });
๐ Important: This works only if
useDolab({ id, fetch })
was already called beforeuseDolabData
in the application lifecycle. That call is what fetches and stores the data initially. From there, any component can subscribe to and reactively use the shared data without duplication or redundant requests.๐ Triggering a Manual Refetch:
You can also manually refetch the stored data when needed โ for example, after submitting a form or on a button click. Simply destructure
triggerRefetch
fromuseDolabData
:const { triggerRefetch: refetch } = useDolabData<Todo[]>({ id: "todos" }); // Example: Trigger refetch on button click <button onClick={refetch}>Refresh Todos</button>
This will re-invoke the
fetch
function defined inuseDolab
for the sameid
and update the stored data accordingly.
๐งช Live Demo
Want to try it out? Hereโs a live playground with examples and integration demos:
๐ Open on CodeSandbox
๐ง Best Practices
- Use
useDolab
once to fetch and store the data. - Use
useDolabData
in child components to access the shared data. - Customize
lifeTime
to control cache expiry. - Pass
deps
to auto-refetch on param/state changes.
๐ฆ npm Package
๐ View on npm
๐ฅ npm install dolab
โ๏ธ Author
- ๐งโ๐ป @abdoseadaa on Dev.to
- ๐ฆ @abdoseadaa on X (Twitter)
- ๐ผ LinkedIn Profile
Top comments (2)
๐๐๐ค๐ค ููู ุงูุนุธู ุฉ
ุฌูุดู