# Can I use React hooks inside a conditional? 

> Can you call React hooks inside a conditional? No, and here is why it breaks the order of hooks, plus how I fixed it by passing null to the useSWR hook.

Author: Flavio Copes | Published: 2020-10-24 | Canonical: https://flaviocopes.com/react-hooks-conditionals/

No.

I do not know _why_ technically, but it's not possible.

I stumbled on this while working with SWR and in particular the `useSWR` hook.

```js
const ({ data } = useSWR(`/api/user`, fetcher)
```

I wanted to only retrieve some data from an API when the user was logged in, and I thought "ok, I can do this":

```js
let data

if (loggedIn) {
  ;({ data } = useSWR(`/api/user`, fetcher)
}
```

but.. no.

[React](https://flaviocopes.com/react/) will raise errors in the console, maybe an error that reads:

> Warning: React has detected a change in the order of Hooks called by Course. This will lead to bugs and errors if not fixed.

The solution will be different depending on the hook used. In this case a very quick and efficient solution was provided by the `useSWR` hook, because I could pass `null` instead of the API endpoint to avoid loading the data:

```js
const ({ data } = useSWR(loggedIn ? `/api/user` : null, fetcher)
```

I moved the conditional _inside_ the hook call, and this made it work for me.
