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
datafunction along with optionalbeforeandafterhooks. Both hooks receiveDataFunctionParams(including the cache key and any response data).// Correct: Using before/after hooks for side effectsuseFetch({key: ['product', id],data: () => actionGetProduct(id),before: async (params) => {// Logic to execute before fetching startsconsole.log('Fetching product...', params.key);},after: async (params) => {// Logic to execute after fetching completesif (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
useEffectclean and ensures the logic runs exactly when the data client executes the request.
Why
- Orchestrate logic around the fetch lifecycle without extra
useEffectcalls. - Access internal fetch parameters like the final resolved key and response status.
- Encapsulate data-related side effects within the action definition.