Skip to main content

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 enabled to 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 authenticated
    const { 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 enabled prop exists, avoid using it to conditionally render components. If enabled is false, no Promise is thrown (if suspense: true), and the component renders with data as undefined. This can lead to runtime errors if your component logic assumes data is present. Instead, conditionally render the component itself.
    // Avoid this: If `id` is missing, `data` is `undefined`, but component renders
    const { data } = useFetch(
    ['user', id],
    () => fetchUser(id),
    { enabled: !!id } // If id is missing, data is undefined, but component renders
    );

    // UserProfile might break if `data` is undefined
    return <UserProfile data={data} />

    // Instead: Conditionally render the component
    {id && <UserProfile id={id} />}
    // Inside UserProfile: `id` is guaranteed
    const { data } = useFetch(['user', id], () => fetchUser(id), {});