DEV Community


Posted on

How to make http request with React Hooks?

This is my first post at I'm going to introduce a custom React Hooks that help making http request -- use-request

I have seen a lot of request libraries written with React Hooks but none of them I like. Most of them put the client in it which causes less flexibility. When switch to use-request, it’s up to you to use axios or fetch. Pass the function that encapsulates the client and the api request into the useRequest function, then you can get the state of the request and callback functions. With typescript support, the input parameters of the request callback function can also be displayed accurately according to the type definition of api function. Let's take a look at how it works!


  • πŸ‘• Typescript support.
  • πŸ—œοΈ 1.3kb after minified without gzip.
  • πŸ“€ Easy to use with different request client.


yarn add @rekindle/use-request


import useRequest from '@rekindle/use-request'
import getFooApi from '@/utils/axios'

function App() {
  const [{ loading, error, data }, fetch] = useRequest(getFooApi)

  function handleClick() {

  useEffect(() => {
  }, [fetch])

  if (loading) return <div>loading...</div>
  if (error) return <div>error</div>

  return (
      <p>{data && data.text}</p>
      <button onClick={handleClick}>refetch</button>


type useRequest = (api, initialState) => [state, memoizedRequestCallback]

Notice: Why momoized request callback ?

Reference: Is it safe to omit functions from the list of dependencies?

If you want a deep dive on useEffect and dependencies, it's here:

Top comments (0)