Using the skip Option in Redux Toolkit Query

The skip option in Redux Toolkit Query (RTK Query) is a simple yet powerful feature that prevents unnecessary API calls when certain conditions aren’t met. Here's a quick guide on how and when to use it.

What is the skip Option?

In RTK Query, the skip option allows you to prevent a query from executing based on a condition. It accepts a boolean value:

  • true: Skips the query (does not execute).

  • false: Executes the query as usual.

Why Use skip?

skip is useful when an API query depends on dynamic values like a courseId, userId, or form data that may not always be available. For example, you wouldn't want to call an API without the necessary parameters, as it would result in errors or wasted network requests.

Example

Here’s an example from a React component where we conditionally fetch course faculties based on the availability of a courseId:

const { data: facultiesData, isFetching: fetchingFaculties } =
  useGetCourseFacultiesQuery(courseId, { skip: !courseId });
  • If courseId is null, undefined, or 0, the query will be skipped.

  • Once a valid courseId is available, the query will execute and fetch the faculties.

Use Cases for skip

  1. Conditional API Calls: Prevent fetching data when required parameters are missing (e.g., courseId, userId).

  2. Form Submissions: Only fetch data after form fields are validated.

  3. Dependent Queries: Skip a query until a prior query provides the necessary data.

Key Benefits

  • Prevents unnecessary API calls.

  • Reduces errors caused by missing parameters.

  • Optimizes performance by avoiding redundant network traffic.

By using the skip option, you ensure your queries only run when they should, improving both performance and reliability.