Getting Started
Installation
Install http-react using your preferred package manager:
yarn add http-reactnpm install http-reactQuick Start
The simplest way to get started is to use useFetch directly in your components:
import useFetch from 'http-react'
export default function App() {
const { data, isPending, error, responseTime } = useFetch('/api/user-info', {
refresh: '30 sec'
})
if (isPending) return <p>Loading...</p>
if (error) return <p>An error occurred</p>
return (
<div>
<h2>Welcome, {data.name}</h2>
<small>Profile loaded in {responseTime}ms</small>
</div>
)
}This example fetches user data and automatically refreshes it every 30 seconds.
Custom Fetcher (Optional)
By default, http-react uses the native fetch API. You can customize this behavior by providing your own fetcher function:
// Default fetcher
const fetcher = (url, config) => fetch(url, config)You can use any HTTP library, such as axios:
import axios from 'axios'
const fetcher = (url, config) => axios(url, config)Your custom fetcher must return an object with data and status properties. Alternatively, you can return an object with a json() method that resolves to the data.
Pass your custom fetcher to useFetch:
const { data, isPending, error } = useFetch('/api/user-info', {
refresh: '30 sec',
fetcher
})Global Configuration (Optional)
Use the FetchConfig component to set global defaults for all requests in your app:
import { FetchConfig } from 'http-react'
export default function App() {
return (
<FetchConfig
baseUrl='/api'
refresh={30}
headers={{ Authorization: 'Bearer token' }}
value={{
'GET /todos': [] // Fallback value for useFetch('/todos')
}}
>
<div>
<h2>My App</h2>
</div>
</FetchConfig>
)
}This allows you to configure:
- Base URL for all requests
- Default refresh intervals
- Global headers (like authentication tokens)
- Fallback values for specific endpoints
- Suspense boundaries for server-side rendering
FetchConfig works with both client components and React Server Components.