Vue · Middle · Question 57 of 75

How can you create a ref that debounces updates?

function useDebouncedRef(value, delay = 300) {
  let timer
  return customRef((track, trigger) => ({
    get() { track(); return value },
    set(v) { clearTimeout(timer); timer = setTimeout(() => { value = v; trigger() }, delay) },
  }))
}

Explanation

customRef gives explicit control over tracking. It can be used with v-model like a normal ref.

Further reading

Problem with a question

Vue · Middle · question 57

Test yourself

Take the Vue · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz