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

CSS only Click-handlers You Might not be using, but you should

  You’re building a simple website, a good-looking landing page with a “See More” button. Instinctively, you reach for JavaScript to handle the button click event. But wait — what if I told you that CSS alone could do the job? Yes. CSS is often underestimated, but it can handle click interactions without JavaScript. In this guide, you’ll learn how to create CSS-only click handlers using the :target pseudo-class, and explore scenarios where this approach makes perfect sense. The :target Pseudo-Class CSS offers several pseudo-classes that let you style elements based on different states ( :hover , :focus , :checked ). But there’s one you might not have used before —  :target . The :target pseudo-class applies styles to an element when its ID matches the fragment identifier in the URL (the part after # ). This behavior is commonly seen when clicking an anchor link that jumps to a section on the same page. Here’s a simple example : <a href="#contact">Go to Contact</...

The 10 Best New CSS Features in 2025 Already Supported in All Major Browsers

  CSS keeps evolving with new capabilities that make our work faster, cleaner, and more powerful. Thanks to the latest browser advances (Baseline 2024), many fresh features now work across all major engines. Below are ten highlights you can start using right away. Do you want more? Let’s check out my project, CSSToday: csstoday.dev/ 1. Scrollbar-Gutter & Scrollbar-Color When a browser displays a scrollbar, the layout can shift as space is taken up. With scrollbar-gutter , you can preserve scrollbar space even before scrolling begins: .scrollable {   scrollbar-gutter : stable both-edges; } You can also style your scrollbars with scrollbar-color : .scrollable {   scrollbar-color : #444 #ccc ; } This ensures a consistent look and prevents layout jumps. What it’s good for ✅ scrollbar-gutter keeps layouts stable by reserving space for a scrollbar, preventing annoying shifts when the scrollbar appears. scrollbar-color lets you style the scrollbar’s track and thumb, en...

Sharpen Your Front-End Skills: Quick HTML, CSS & React Interview Challenges

  The source of this image is Chat GPT based on writing! Are you preparing for front-end developer interviews and looking for practical, hands-on ways to improve your HTML, CSS, and React skills? Whether you’re a beginner aiming to build confidence or an experienced developer brushing up on UI skills, small, targeted challenges can make a huge difference. In this article, I’ll walk you through some of the best free and low-cost resources that offer real-world front-end tasks — perfect for interview prep, portfolio building, and daily practice. 1. Frontend Mentor frontendmentor.io Frontend Mentor is one of the most popular platforms for hands-on HTML, CSS, and JavaScript challenges. You get beautifully designed templates (in Figma or image formats) and are asked to bring them to life using clean code. The platform offers difficulty levels ranging from newbie to expert, and it’s perfect for practicing responsiveness and semantic HTML. Bonus : You can even filter for React-based ...