reactjsreact-hooksreact-custom-hooksusefetch

React hooks calling with ternary operations


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


Solution

  • 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