Skip to content

Can I use React hooks inside a conditional?

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.

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”:

let data

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

but.. no.

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:

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

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


→ Get my React Beginner's Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about react: