useFetch

Fetch data with accurate states, caching, and no stale responses using useFetch.

Install:

Note: This hook depends on React’s experimental useEffectEvent.

npm i @uidotdev/usehooks@experimental react@experimental react-dom@experimental

Description:

The useFetch React hook is useful for handling data fetching and state management in React components. It allows you to easily fetch data from a specified URL using the fetch API and provides a consistent pattern for handling loading, success, and error states. It also incorporates an internal caching mechanism to store and retrieve previously fetched data, improving performance by reducing redundant network requests. Additionally, it includes a mechanism to ignore stale responses if the component unmounts or if a new request is made before the previous one completes.

Parameters

NameTypeDescription
urlstringThe URL to fetch data from.
optionsobject(Optional) Additional options for the fetch request, such as headers or request methods.

Return Values

NameTypeDescription
stateobjectThe state object containing the fetched data and error status.
state.errorerror | undefinedThe error object if an error occurred during the fetch, otherwise undefined.
state.dataany | undefinedThe fetched data if the fetch was successful, otherwise undefined.

Demo:

Example:

More Hooks:

Sort: