Reusing Requests
When you use the same request across multiple components, http-react automatically shares the request state and prevents duplicate network calls. The library tracks whether requests are loading, completed, or failed, and synchronizes this state across all components using useFetch or its variants (useData, useLoading, etc).
Creating Reusable Request Hooks
Define a custom hook that encapsulates your request configuration:
import useFetch from 'http-react'
function useUserInfo() {
return useFetch('/api/user-info', {
headers: {
Authorization: 'my-token'
},
cache: 'only-if-cached',
mode: 'cors'
})
}You can include any standard fetch options like keepalive, cache, or method.
Using the Hook Across Components
Call your custom hook in any component that needs the data:
function UserInfo() {
const { data, loading, error } = useUserInfo()
if (loading) return <p>Loading...</p>
if (error) return <p>An error occurred</p>
return (
<div>
<p>Username: {data.name}</p>
</div>
)
}
function AccountBalance() {
const { data, loading, error } = useUserInfo()
if (loading) return <p>Loading account balance...</p>
if (error) return <p>Unable to get account balance</p>
return (
<div>
<p>Balance: {data.accountBalance}</p>
</div>
)
}
export default function Page() {
return (
<div>
<UserInfo />
<AccountBalance />
</div>
)
}Automatic Request Deduplication
Even though useUserInfo is called in both components, only one network request is made. This request deduplication (opens in a new tab) ensures efficient data fetching. Both components automatically:
- Share the same loading state
- Receive the same data when the request completes
- Update simultaneously when the request state changes
No additional configuration is required - http-react handles this automatically.