---
sidebar_position: 3
title: React hooks - useFetch
sidebar_label: useFetch
---

# useFetch

<div class="api-link">
  <div class="api-link-title">useFetch</div>
  <div class="api-link-sub-title">

[Read the API Reference »](/api/React/Hook/useFetch.mdx)

  </div>
</div>

---

## Introduction

This hook is created to **retrieve data** from the server. It uses the
[`Fetch Dispatcher`](/documentation/02-core/dispatcher.mdx) to handle requests and the
[`Cache`](/documentation/02-core/cache.mdx) to manage the overall state of the data.

A prepared Request is the minimum requirement for useFetch.

If you intend to `mutate` data stored on the server, we recommend choosing the
[`useSubmit`](/documentation/04-react/02-core/use-submit.mdx) hook.

---

## Initialization

```tsx
const { data, error, loading, onSuccess, onError, onFinished } = useFetch(getUsers);
```

---

## How it works?

**`useFetch`** executes a request when a component is mounted or when its dependencies array changes. It uses dependency
tracking to limit re-rendering and help with performance.

Under the hood, communication with the core systems is established by event emitters. There are many `"helper hooks"`
that get returned from the hook, like `onSuccess`, `onError`, and `onFinished` (among others). They will help you handle
various events in the request flow and lifecycle.

We used this approach to avoid overloading the base hook with callback logic, which causes low code readability and
increases complexity.

```tsx
import { useFetch } from "@hyper-fetch/react";
import { getUsers } from "server";

const UsersListPage: React.FC = () => {
  const { data, error, loading, onSuccess, onError, onFinished } = useFetch(getUsers);

  onSuccess(({ response }) => {
    console.log(response); // [ User, User, User ]
  });

  onError(({ response }) => {
    console.log(response); // { message: string }
  });

  onFinished(({ response }) => {
    const [payload, error, status] = response;
    console.log(payload); // [ User, User, User ] | null
    console.log(error); // { message: string } | null
    console.log(status); // 200 / 400 / 404 / 500 ...
  });

  return (
    <div>
        {loading && <Loader>}
        {!loading && error && <Alert severity="error">{error.error_message}</Alert>}
        {!loading && !error && !data.length && <div>List is empty</div>}
        {!loading && !error && data.length && <div>{data.map(user => <div>{user.name}</div>)}</div>}
    </div>
  );
};
```

---

## Options

Configuration options for `useFetch` must be provided as the second parameter.

```tsx
const { ... } = useFetch(request, options)
```

{@import React UseFetchOptionsType returns}

---

## Returns

Returned values from this hook.

```tsx
const values = useFetch(request);
```

{@import React UseFetchReturnType returns}
