/

Can React hooks be used inside a conditional?

Can React hooks be used inside a conditional?

No, React hooks cannot be used directly inside a conditional statement. While it may seem like a viable solution to conditionally call a hook based on a certain condition, it is not technically possible.

During the rendering phase, Hooks need to be called in the same order on every render. React uses the order of hooks to ensure consistency and prevent bugs. Placing a hook inside a conditional can disrupt this order and lead to errors.

For example, consider using the useSWR hook from the SWR library to fetch data from an API:

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

If you try to conditionally call this hook based on a variable like loggedIn, you will encounter errors:

1
2
3
4
5
6
let data

if (loggedIn) {
// This will cause errors
({ data } = useSWR(`/api/user`, fetcher)
}

React will raise an error in the console similar to:

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

To work around this limitation, you can move the conditional inside the hook call by passing null as the API endpoint when the condition is not met:

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

By doing this, the conditional logic is handled within the hook itself and enables the desired behavior.

Tags: React hooks, conditional rendering, SWR hook, useSWR hook