Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
U

use-http

> 前端框架
Open source

React hook for making isomorphic http requests

2.3K stars0 likes2 views
WebsiteGitHub

About

React hook for making isomorphic http requests

[![use-http logo][3]][5]


useFetch






Features

  • SSR (server side rendering) support
  • TypeScript support
  • 2 dependencies (use-ssr, urs)
  • GraphQL support (queries + mutations)
  • Provider to set default url and options
  • Request/response interceptors
  • React Native support
  • Aborts/Cancels pending http requests when a component unmounts
  • Built in caching
  • Persistent caching support
  • Suspense(experimental) support
  • Retry functionality

Usage

Examples + Videos

  • useFetch - managed state, request, response, etc.
  • useFetch - request/response interceptors
  • useFetch - retries, retryOn, retryDelay
  • useFetch - abort, timeout, onAbort, onTimeout
  • useFetch - persist, cache
  • useFetch - cacheLife, cachePolicy
  • useFetch - suspense (experimental)
  • useFetch - pagination
  • useQuery - GraphQL
  • useFetch - Next.js
  • useFetch - create-react-app
Basic Usage Managed State useFetch

If the last argument of useFetch is not a dependency array [], then it will not fire until you call one of the http methods like get, post, etc.

…

Basic Usage Auto-Managed State useFetch

This fetch is run onMount/componentDidMount. The last argument [] means it will run onMount. If you pass it a variable like [someVariable], it will run onMount and again whenever someVariable changes values (aka onUpdate). If no method is specified, GET is the default.

javascript
import useFetch from 'use-http'

function Todos() {
  const options = {} // these options accept all native `fetch` options
  // the last argument below [] means it will fire onMount (GET by default)
  const { loading, error, data = [] } = useFetch('https://example.com/todos', options, [])
  return (
    <>
      {error && 'Error!'}
      {loading && 'Loading...'}
      {data.map(todo => (
        

      ))}
    </>
  )
}
Suspense Mode(experimental) Auto-Managed State

Can put suspense in 2 places. Either useFetch (A) or Provider (B).

javascript
import useFetch, { Provider } from 'use-http'

function Todos() {
  const { data: todos = [] } = useFetch('/todos', {
    suspense: true // A. can put `suspense: true` here
  }, []) // onMount

  return todos.map(todo => 
)
}

function App() {
  const options = {
    suspense: true // B. can put `suspense: true` here too
  }
  return (
    <Provider url='https://example.com' options={options}>
      <Suspense fallback='Loading...'>
        <Todos />
      </Suspense>
    </Provider>
  )
}

Suspense Mode(experimental) Managed State

Can put suspense in 2 places. Either useFetch (A) or Provider (B). Suspense mode via managed state is very experimental.

…
Pagination + Provider

The onNewData will take the current data, and the newly fetched data, and allow you to merge the two however you choose. In the example below, we are appending the new todos to the end of the current todos.

…

Destructured useFetch

⚠️ Do not destructure the response object! Details in this video. Technically you can do it, but if you need to access the response.ok from, for example, within a component's onClick handler, it will be a stale value for ok where it will be correct for response.ok. ️️⚠️

…

Relative routes useFetch
javascript
var request = useFetch('https://example.com')

request.post('/todos', {
  no: 'way'
})

Abort useFetch
javascript
const { get, abort, loading, data: repos } = useFetch('https://api.github.com/search/repositories?q=')

// the line below is not isomorphic, but for simplicity we're using the browsers `encodeURI`
const searchGithubRepos = e => get(encodeURI(e.target.value))

<>
  <input onChange={searchGithubRepos} />
  <button onClick={abort}>Abort</button>
  {loading ? 'Loading...' : repos.data.items.map(repo => (
    

  ))}
</>

GraphQL Query useFetch
javascript

const QUERY = `
  query Todos($userID string!) {
    todos(userID: $userID) {
      id
      title
    }
  }
`

function App() {
  const request = useFetch('http://example.com')

  const getTodosForUser = id => request.query(QUERY, { userID: id })

  return (
    <>
      <button onClick={() => getTodosForUser('theUsersID')}>Get User's Todos</button>
      {request.loading ? 'Loading...' : <pre>{request.data}</pre>}
    </>
  )
}
GraphQL Mutation useFetch

The Provider allows us to set a default url, options (such as headers) and so on.

javascript

const MUTATION = `
  mutation CreateTodo($todoTitle string) {
    todo(title: $todoTitle) {
      id
      title
    }
  }
`

function App() {
  const [todoTitle, setTodoTitle] = useState('')
  const request = useFetch('http://example.com')

  const createtodo = () => request.mutate(MUTATION, { todoTitle })

  return (
    <>
      <input onChange={e => setTodoTitle(e.target.value)} />
      <button onClick={createTodo}>Create Todo</button>
      {request.loading ? 'Loading...' : <pre>{request.data}</pre>}
    </>
  )
}
Provider using the GraphQL useMutation and useQuery
Query for todos
…

Add a new todo
…
Adding the Provider

These props are defaults used in every request inside the <Provider />. They can be overwritten individually

javascript
import { Provider } from 'use-http'
import QueryComponent from './QueryComponent'
import MutationComponent from './MutationComponent'

function App() {

  const options = {
    headers: {
      Authorization: 'Bearer YOUR_TOKEN_HERE'
    }
  }
  
  return (
    <Provider url='http://example.com' options={options}>
      <QueryComponent />
      <MutationComponent />
    <Provider/>
  )
}
Request/Response Interceptors

This example shows how we can do authentication in the request interceptor and how we can camelCase the results in the response interceptor

…

File Uploads (FormData)

This example shows how we can upload a file using useFetch.

javascript
import useFetch from 'use-http'

const FileUploader = () => {
  const [file, setFile] = useState()
  
  const { post } = useFetch('https://example.com/upload')

  const uploadFile = async () => {
    const data = new FormData()
    data.append('file', file)
    if (file instanceof FormData) await post(data)
  }

  return (
    

  )
}
Handling Different Response Types

This example shows how we can get .json(), .text(), .formData(), .blob(), .arrayBuffer(), and all the other http response methods. By default, useFetch 1st tries to call response.json() under the hood, if that fails it's backup is response.text(). If that fails, then you need a different response type which is where this comes in.

javascript
import useFetch from 'use-http'

const App = () => {
  const [name, setName] = useState('')
  
  const { get, loading, error, response } = useFetch('http://example.com')

  const handleClick = async () => {
    await get('/users/1?name=true') // will return just the user's name
    const text = await response.text()
    setName(text)
  }
  
  return (
    <>
      <button onClick={handleClick}>Load Data</button>
      {error && error.messge}
      {loading && "Loading..."}
      {name && 
}
    </>
  )
}

<

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptfetchfetch-datagraphqlhttp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架