React hooks calling with ternary operations

83 Views Asked by At

const allUsers = useFetch(fetchUsersApi, [id]); const usersWithoutAccess = useFetch(fetchUsersApi, [id, queryParams]); const { data: permission } = useFetch(fetchPermissionApi, [id]); const users = permission.value ? allUsers : usersWithoutAccess;

1

There are 1 best solutions below

4
On BEST ANSWER

No, you cannot call hooks conditionally1. Every time you render you must call exactly the same hooks in exactly the same order. If you don't, react can't tell which hook corresponds to which, so it can result in things like the wrong state being returned from a useState hook.

Fixing this typically is done one of two ways:

  1. Modify the hook so you can pass in a parameter to disable it. Eg, null could indicate that it should not fetch.
  2. Split the code into a separate component, and only render that component when you want to fetch.

If you'd like details on how to do these, please edit your question to include the code for useFetch

1) Except for the upcoming use hook