#5498·vueuse

`useLoading` | A hook records function's execute state

Author: ZacharyBearCreated Jun 8, 2026Updated Aug 25, 2026

Clear and concise description of the problem

I want a function is familiar to React's useTransition API. It wraps a function, provides pending state and wrapped start function:

@/apis/user.js

typescript
const fetch = async (userId) => () => {
  return await axios.request('/api/user/' + userId)
}

Using in Vue SFC:

xml
<script lang='ts' setup>
import userApi from '@/apis/user'

const [fetchingUser, fetchUser] = useLoading(userApi.fetch)
</script>

<template>
  <section>
    <button @click='fetchUser'>Load User Information</button>
    <p v-show='fetchingUser'>Please wait... =)</p>
  </section>
</template>

Suggested solution

Here is an simple implementation wroten by JavaScript and JSDoc.

javascript
/**
 * An hook wraps asynchronous function, provides pending state and start function.
 * Ref to React useTransition: https://zh-hans.react.dev/reference/react/useTransition
 *
 * @template {Function} T
 * @param {T} fn An asynchronous function
 * @returns {[pending: Ref<boolean>, start: T]} Wrapped array result
 * 
 * pending: Is this function running
 * start: Start run this function
 */
export const useLoading = (fn) => {
  const loading = ref(false)

  const start = async (...params) => {
    loading.value = true
    try {
      return await fn(...params)
    } catch (e) {
      console.error(e)
      throw e
    } finally {
      loading.value = false
    }
  }

  return [loading, start]
}

It allows developers to pass parameters in to the wrapped start function, and will return the promised result to the caller.

Alternative

No response

Additional context

Using an array for the result requires developers to assign names to each part, which helps avoid variable name collisions:

javascript
const [fetching, fetch] = useLoading(userApi.fetch)
const [removing, remove] = useLoading(userApi.remove)
const [updating, update] = useLoading(userApi.update)
// Other pendings and starts...

Validations