Skip to main content

This One React Hook Streamlines Every Project I Build

 


I’m debugging a React app for a client who insists the page should update “instantly” when users click a button.

I’m knee-deep in state variables, loading flags, try-catch blocks, and a mental breakdown.

My useEffect Looks like a spaghetti monster mated with a JSON dump.

Then it hits me: Why the hell am I writing this boilerplate over and over again?

That night, I built the one hook that changed everything: useAsync().



Edited by me

The Nightmare That Birthed a Hook

You’ve probably lived this too. Fetching data? Here comes a mess of:

const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch(url)
.then((res) => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [url]);
Gross. Repetitive. Bug prone.

So I ripped it out. Abstracted it. And gave it a new home:

Say Hello to useAsync()

Here’s what it looks like:

const { data, error, loading, run } = useAsync();
useEffect(() => {
run(() => fetchDataFromAPI());
}, []);

Or even better:

const { data, loading, error } = useAsync(() => fetchDataFromAPI(), []);
Clean. Declarative. Sexy.

No more duplicating loading state logic.

No more 8 lines of async wrappers per component.

Just pass your function. The hook handles the ugly parts.

What It Does (Under the Hood)

The hook accepts an async function, executes it, and tracks:

  • loading: boolean (self-explanatory)
  • errorThe caught error object
  • data: the resolved value

It handles cancellation (yep, no memory leaks from zombie fetches). And you can trigger it on mount or manually via .run().

Here’s the core idea:

function useAsync(fn, deps = []) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const run = useCallback(async () => {
setLoading(true);
setError(null);
try {
const result = await fn();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
}, deps);
useEffect(() => {
if (fn) run();
}, [run]);
return { data, error, loading, run };
}

Why You’ll Want It Too

Let’s be honest.

Frontend work is already chaotic.

We juggle user events, server responses, global state, and UX edge cases like a caffeinated octopus.

So anything that:

  • Reduces repeated patterns
  • Makes components cleaner
  • Handles loading/error logic once and forever

…is worth tattooing on your IDE.

This hook turned my janky useEffect-graveyards into clean, readable, business-logic-focused components.

But Wait — Why Not React Query or SWR?

Great tools. Love ’em.

Use them on bigger apps. But sometimes?

You just need a lightweight custom hook.

No config. No caching. No dependency injection. Just pure async logic control.

Think: internal dashboards, admin panels, MVPs. Places where simplicity wins.

This hook is my go-to in those cases. And it never lets me down.

Reality — This Hook Saves You From Yourself

Because let’s be real: it’s not just about code reusability. It’s about,

  • Preventing bugs when you forget to reset loading
  • Avoiding nested try-catch hell
  • Making junior devs say, “Whoa, that’s clean.”

It’s a form of self-care. The React version of drinking enough water.

Finally, You Deserve Clean Code

If you’re writing async logic in React and not abstracting it, you’re wasting time and sanity.

useAsync() Is a tiny hook with big benefits. Make it. Customize it. Use it.

Hell, tattoo it on your forehead if you must.

What’s your go-to hook?
Have you built your own useAsync variant?
Still clinging to useEffect spaghetti?

Drop a comment. Start a flame war. Or just clap if you felt the same pain.

Let’s talk hooks.

Comments

Popular posts from this blog

Exploring Google’s New Gemini CLI: The Ultimate Open-Source Dev Tool

  Google quietly released a local AI agent that builds apps, debugs code, parses your repo, and fetches real-time data, right inside your terminal. And it’s completely free. This year, the most revolutionary developer tools I’ve used didn’t come with a splashy launch or billion-dollar hype. It came as a simple CLI: Gemini CLI, a terminal-based AI agent built on top of Google’s Gemini 2.5 Pro model . At first glance, it looks like a lightweight alternative to Claude Code. But after just 10 minutes of use, it became clear: this isn’t just a convenient utility. It’s a powerful local AI development assistant that can analyze, automate, and accelerate almost every part of your software workflow. And best of all? It’s fully open-source under the Apache 2.0 license It gives you up to 1,000 free requests per day It integrates with your local filesystem, IDE, and the web And it runs entirely in your terminal , no browser needed In this guide, I’ll show you what Gemini CLI is, how it works...

6 Essential JavaScript Concepts Every Developer Should Understand

It’s the only language I’ve used where [] == ![] it's true and where you can, typeof null and somehow get 'object' . But despite all its quirks (and there are many), there are a few core concepts that make life with JS not just easier, but saner. This isn’t some computer science flex. These are practical concepts that, once you understand them, make you write better, cleaner, and less buggy code. 1. Hoisting  Before you rage at your variables being undefined , understand this: JS hoists variable and function declarations to the top of their scope. But —  and this is important  —  only the declarations , not the assignments. Why? Because JS reads it like: This is also why let and const behave differently — they’re hoisted too, but live in the “Temporal Dead Zone” until declared. 2. Closures Closures are like little memory vaults for your functions. They allow functions to remember variables from the scope they were created in, even after that scope has gone. Why care? T...

Top 25 JavaScript Array Methods Every Developer Should Learn

  You wrote some code. You ran it. And then your array went from a list of users to an angry collection of undefined , NaN And more bugs than a summer camping trip. Staring at map , filter , and reduce like they were ancient scrolls written in Elvish. Copy-pasting from Stack Overflow like a caffeinated zombie. Wondering why the heck splice just murdered half my data. But here’s the truth: mastering arrays is non-negotiable. If you’re fumbling with arrays, you’re fumbling with everything . Web apps, APIs, UIs — they all depend on your ability to tame this glorious beast. So buckle up. I’m about to drop 25 methods that will make you look at arrays like a surgeon looks at a scalpel. Edited by me 1. map() - Because Loops Are for Cavemen You want to transform every item in an array? Don’t go forEach your way to hell. map It is concise, expressive, and doesn’t mutate your data. It’s like therapy for arrays. const names = [ 'alice' , 'bob' , 'charlie' ]; const u...