React Hooks: Can I use React hooks inside a conditional?

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


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.

Lessons in this unit:

0: Introduction
1: Introduction to React Hooks
2: How to use the useState React hook
3: useEffect React hook, how to use
4: How to use the useContext React hook
5: How to use the useReducer React hook
6: How to use the useCallback React hook
7: How to use the useMemo React hook
8: How to use the useRef React hook
9: ▶︎ Can I use React hooks inside a conditional?
10: Why does useEffect run two times?
11: Using useState with an object: how to update
12: How to reference a DOM element in React