# React Query Retry explained

## What is React Query

React query or as it is now called Tanstack Query is a library that helps you fetch, cache and update data in your React applications. It's a great tool to completely replace your fetching and state management / caching logic and separating your state into, remote, app and local as advised by my guide on [The Three States of React](/blog/the-three-states/)

## What is `retry` in React Query

`retry` is an option that you can pass into your react query that will basically tell it to retry fetching the data if it fails. You can control it further by passing either a number of times for it to retry(default is 3), telling it to retry indefinitely (not advised unless you have a very specific use case) or passing a callback that will allow you to write your own logic when and how to retry or what to do on a retry.

to sum it up:

* `retry = false` will disable retrying
    
* `retry = number` will retry that number of times e.g `retry = 5` will retry 5 times
    
* `retry = true` will retry indefinitely again only do this if you are sure you want to retry indefinitely
    
* `retry = (failureCount, error) => boolean` will allow you to write your own logic and give you access to the number of times it has failed and the error that caused the failure.
    

## How to use `retry` in React Query

It's perfectly simple and straightforward to use retry in React Query. You just need to pass it as an option to your query like so:

```javascript
const data = useQuery(['someKey'], fetchData, {
  retry: 5
})
```

That's a very simple and basic example right and you can kinda see how you can use the rest of the options stated above in here, so I won't waste your time with more examples.

I will however show you some cool stuff you can do with this.

## Cool stuff you can do with `retry` in React Query

### Show a toast on failure

You can use the `retry` callback to show a toast on failure like so:

```javascript
const data = useQuery(['someKey'], fetchData, {
  retry: (failureCount, error) => {
    toast.error(`Failed to fetch data: ${error.message}`)
    return failureCount < 5
  }
})
```

### Implement exponential backoff

Exponential backoff is a technique that will increase the time between retries exponentially. This is a great way to reduce the load on your server and make your app more resilient to network failures. You can implement it like so:

```javascript
const data = useQuery(['someKey'], fetchData, {
  retry: (failureCount, error) => {
    const retryDelay = Math.min(1000 * 2 ** failureCount, 30000)
    setTimeout(() => {
      queryClient.invalidateQueries('someKey')
    }, retryDelay)
    return failureCount < 5
  }
})
```

### Implement custom logging or error handling

You can also use the `retry` callback to implement custom logging or error handling like so:

```javascript
const data = useQuery(['someKey'], fetchData, {
  retry: (failureCount, error) => {
    Logger.log(
      `${date}: Failed to fetch data, ERROR: ${error.message}`
    )
    console.error(`Failed to fetch data: ${error.message}`)
    return failureCount < 5
  }
})
```

### Implement a custom retry strategy

Let's say that you know that your server is going to be down for maintenance every so often and during that time it will return a 503(service unavailable) error. You can implement a custom retry strategy like so:

```javascript
const data = useQuery(['someKey'], fetchData, {
  retry: (failureCount, error) => {
    if (error.status === 503) {
      return false
    }
    return failureCount < 5
  }
})
```

The above code will retry 5 times unless the error is a 503 in which case it will stop retrying. You could even hook this up to a toast or a notification to let the user know that the server is down for maintenance.

## Conclusion

`retry` is a simple yet very powerful option in React Query/Tanstack Query that can make your app more resilient to network failures and give you far more control over your fetching logic than you would have with a simple fetch or axios call. I hope this article has given you some ideas on how to use it in your own projects.
