Managing the loading, success, and error states of asynchronous operations is a fundamental aspect of most React applications. However, developers often find themselves integrating comprehensive libraries like TanStack React Query or Redux Toolkit for this purpose, even when their needs are relatively simple. These powerful libraries, while excellent for complex data fetching and global state management, can sometimes introduce unnecessary overhead and complexity for straightforward async actions.
This article introduces a lightweight alternative: @t8/react-pending
. This small, focused package offers an elegant solution for tracking the pending and error states of async actions without requiring a complete overhaul of your application’s state management or the async functions themselves. It provides a clear and non-intrusive way to manage these states, either locally within a component or shared across multiple components when needed.
The core of @t8/react-pending
is the usePendingState
hook. With just a few lines of code, you can wrap your existing async calls to automatically track their lifecycle. For instance, you would simply import usePendingState
, initialize it, and then use the returned withState
function to execute your async operation. This allows you to easily display “Loading…” messages, “An error occurred” notifications, or your actual data, depending on the current state of the async action.
A key benefit is its flexibility: the data itself can reside in any existing state management solution (local component state, Context API, etc.), as @t8/react-pending
focuses solely on the state of the action. Furthermore, by providing a unique key to usePendingState
, you can share the loading and error status of a specific async operation across different components, enabling coordinated UI updates (e.g., a main content area showing a loader and a separate status bar showing “Busy”). If the state is only needed within a single component, the key can be omitted for even simpler usage.
In summary, when the full power of a comprehensive data fetching library feels like overkill for managing the status of an async action, @t8/react-pending
provides a minimalist, single-purpose library that cleanly handles pending and error states, keeping your code focused and your dependencies light. It’s an ideal choice for streamlining async UI feedback without disrupting your existing application architecture.