React hooks in Axios interceptors
Tags: react, axios, javascript
Published: 2022-03-29 17:38:19

As you know, you can not use React hooks in a place other than React component or custom hooks.

In this article, you will learn how to use hooks in the Axios interceptors.

First, create a React project.
```
yarn create react-app hooks-in-axios-interceptors

// or

npx create-react-app hooks-in-axios-interceptors
```

Then create an Axios instance with custom configuration.

```javascript
import axios from 'axios';

const instance = axios.create({
    baseURL: "https://example.com"
})

export default instance;
```


As we need React component to use the hooks, let's write a component here.

```javascript
import axios from 'axios';

let instance = axios.create({
    baseURL: "https://example.com"
}) 

function AxiosInterceptor({children}) {
    return children;
}

export default instance;
export {AxiosInterceptor}
```

Adding an interceptor in a component is a side effect, so we get help from `useEffect` hook.

Add the interceptors to the Axios instance in the `useEffect`.

**Note : you must remove interceptors in `useEffect` return statement, because every execution of `useEffect`, adds a new interceptor to Axios instance.**

```javascript
import axios from 'axios';
import { useEffect } from 'react'

const instance = axios.create({
    baseURL:  "https://example.com"
})

const AxiosInterceptor = ({ children }) => {

    useEffect(() => {

        const resInterceptor = response => {
            return response;
        }

        const errInterceptor = error => {
            return Promise.reject(error);
        }


        const interceptor = instance.interceptors.response.use(resInterceptor, errInterceptor);

        return () => instance.interceptors.response.eject(interceptor);

    }, [])
    return children;
}


export default instance;
export { AxiosInterceptor }
```


Now, you can import the intended hooks and use them in the interceptors handler.
for instance, if you want to redirect the request which come back with the status code 401, to the login page, you may use the `useNavigate` hook ( from react-router-dom ) or use the `useRouter` hook ( from next/router ).

```javascript
import axios from 'axios';
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

const instance = axios.create({
    baseURL:  "https://example.com"
})

const AxiosInterceptor = ({ children }) => {

    const navigate = useNavigate();

    useEffect(() => {

        const resInterceptor = response => {
            return response;
        }

        const errInterceptor = error => {

            if (error.response.status === 401) {
                navigate('/login');
            }

            return Promise.reject(error);
        }


        const interceptor = instance.interceptors.response.use(resInterceptor, errInterceptor);

        return () => instance.interceptors.response.eject(interceptor);

    }, [navigate])

    return children;
}


export default instance;
export { AxiosInterceptor }
```


**Note : as we do not want to destroy the SPA behavior of our application, we don't use `window.location` for redirecting.**

Finally, we wrap the app with the Axios interceptor component.

```javascript
import { AxiosInterceptor } from './axios'
import ThemeProvider from './theme-context'
import AuthProvider from './auth-context'

function App() {
  return (
    <ThemeProvider>
      <AuthProvider>
        <AxiosInterceptor>
          <div>
            App
          </div>
        </AxiosInterceptor >
      </AuthProvider>
    </ThemeProvider>
  );
}

export default App;
```


**Note : if you want to access the other context data, the Axios interceptor component must be the child of the context providers.** 

## Codesandbox Example
{% embed https://codesandbox.io/embed/axios-interceptor-react18-xgo3em?expanddevtools=1&fontsize=14&theme=dark %}


## conclusion
In this way, you can use the React hooks in the Axios interceptors easily.