enabled
Description: Defines if the useFetch hook is active or not. If this is set to false, the action function will not be executed. Use e.g. when you don't want the hook to fire and fetch the data immediatelly on component mount.
Default Value: true.
- How To: Use
enabledto programmatically control when a fetch should run, e.g., based on global state, user permissions or actions, or when any other prerequisite condition is met.// Correct: Fetch only when the user is authenticatedconst { data: user } = useFetch('user', () => actionGetUser(), {});const { data: userSettings } = useFetch(['user-settings', user?.id],() => fetchUserSettings(user.id),{ enabled: !!user?.id } // only fetch settings if user ID is available); - Best Practice: While the
enabledprop exists, avoid using it to conditionally render components. Ifenabledisfalse, no Promise is thrown (ifsuspense: true), and the component renders withdataasundefined. This can lead to runtime errors if your component logic assumesdatais present. Instead, conditionally render the component itself.// Avoid this: If `id` is missing, `data` is `undefined`, but component rendersconst { data } = useFetch(['user', id],() => fetchUser(id),{ enabled: !!id } // If id is missing, data is undefined, but component renders);// UserProfile might break if `data` is undefinedreturn <UserProfile data={data} />// Instead: Conditionally render the component{id && <UserProfile id={id} />}// Inside UserProfile: `id` is guaranteedconst { data } = useFetch(['user', id], () => fetchUser(id), {});