DEV Community

Everkers
Everkers

Posted on

Taming Async Operations in React with use-async-stateful

Hey there, fellow devs! ๐Ÿ‘‹

If you've worked with React for any decent amount of time, you've probably had your fair share of wrestling with asynchronous operations and the accompanying state management. Loading states, error messages, and then finally rendering dataโ€”it can all get a tad repetitive. That's why I decided to create and share use-async-stateful, a React Lightweight Hook designed to alleviate some of that pain.

What Does use-async-stateful Do?

At its core, this hook manages the states commonly associated with async operations. Think loading, error, and success without the fuss of setting and resetting states manually.

import { useAsyncHook } from 'use-async-stateful';

const { status, error, execute } = useAsyncStateful({
  resetStatusOnSuccess: true,
  resetStatusOnError: true,
});

const fetchData = async (id: number) => {
  // Your async logic here
  return `Data for ID: ${id}`
}

// Now, just use `execute` with your async functions!

const handleFetch = async () => {
    const data = await execute(fetchData, 123)
    console.log(data)
}
Enter fullscreen mode Exit fullscreen mode

Features at a Glance

  • Simplified Async State Management: Forget separate loading, error, and data states.
  • One hook to rule them all!
  • Configurable Reset Options: Decide if and when you want to reset your status.
  • TypeScript Support: For the folks who love strong typing, use-async-stateful has got your back.

Getting Started

To integrate use-async-stateful into your project, you can use either npm or yarn:

npm install use-async-stateful
Enter fullscreen mode Exit fullscreen mode
yarn add use-async-stateful
Enter fullscreen mode Exit fullscreen mode

Then, you can follow the example above to integrate it into your components.

Feedback & Contributions

Open-source thrives on community. Whether you have feature suggestions, issues, or want to contribute directly, you're welcome to check out the GitHub repo.

If you find use-async-stateful helpful, consider giving it a star โญ or sharing it with fellow devs.

There you have it! I hope use-async-stateful can make your React adventures a tad smoother. Would love to hear your experiences and feedback in the comments below. Happy coding! ๐Ÿš€

Link to the repository

Top comments (0)