Skip to main content

Lifecycle Hooks (before/after)

Description: Asynchronous hooks that can be executed before and after the data fetching process. These are defined within the action parameter of the useFetch or useMutation hooks.

  • How To: Provide an object as the action parameter instead of a single function. This object should contain the data function along with optional before and after hooks. Both hooks receive DataFunctionParams (including the cache key and any response data).
    // Correct: Using before/after hooks for side effects
    useFetch({
    key: ['product', id],
    data: () => actionGetProduct(id),
    before: async (params) => {
    // Logic to execute before fetching starts
    console.log('Fetching product...', params.key);
    },
    after: async (params) => {
    // Logic to execute after fetching completes
    if (params.response) {
    trackAnalytics('product_view', params.response);
    }
    }
    });
  • Best Practice: Use lifecycle hooks for surgical side effects like logging or analytics that are directly tied to a specific fetch. This keeps your component's useEffect clean and ensures the logic runs exactly when the data client executes the request.

Why

  • Orchestrate logic around the fetch lifecycle without extra useEffect calls.
  • Access internal fetch parameters like the final resolved key and response status.
  • Encapsulate data-related side effects within the action definition.