0
0
Vueframework~7 mins

Custom refs with customRef in Vue

Choose your learning style9 modes available
Introduction

Custom refs let you control how Vue tracks and updates reactive data. They help you create special reactive behaviors beyond the usual ones.

When you want to create a reactive value that updates only under certain conditions.
When you need to customize how Vue tracks dependencies and triggers updates.
When you want to wrap a non-reactive object and make it reactive in a custom way.
When you want to optimize performance by controlling when updates happen.
When you want to add side effects or custom logic during get or set of a reactive value.
Syntax
Vue
import { customRef } from 'vue'

const myRef = customRef((track, trigger) => {
  let value
  return {
    get() {
      track()
      return value
    },
    set(newValue) {
      value = newValue
      trigger()
    }
  }
})

track() tells Vue to track dependencies when the value is read.

trigger() tells Vue to update dependents when the value changes.

Examples
This custom ref only updates if the new value is zero or positive.
Vue
const count = customRef((track, trigger) => {
  let value = 0
  return {
    get() {
      track()
      return value
    },
    set(newValue) {
      if (newValue >= 0) {
        value = newValue
        trigger()
      }
    }
  }
})
This custom ref delays updates by 300ms, useful for debouncing input.
Vue
const debouncedRef = customRef((track, trigger) => {
  let value
  let timeout
  return {
    get() {
      track()
      return value
    },
    set(newValue) {
      clearTimeout(timeout)
      timeout = setTimeout(() => {
        value = newValue
        trigger()
      }, 300)
    }
  }
})
Sample Program

This Vue component uses a custom ref to only update the count if the input is zero or positive. Negative numbers typed in the input will not change the displayed count.

Vue
<template>
  <div>
    <input v-model.number="count" type="number" aria-label="Number input" />
    <p>Count (only positive numbers update): {{ count }}</p>
  </div>
</template>

<script setup>
import { customRef } from 'vue'

const count = customRef((track, trigger) => {
  let value = 0
  return {
    get() {
      track()
      return value
    },
    set(newValue) {
      if (newValue >= 0) {
        value = newValue
        trigger()
      }
    }
  }
})
</script>
OutputSuccess
Important Notes

Use customRef when you need fine control over reactivity.

Always call track() in get() and trigger() in set() to keep Vue's reactivity system working.

Custom refs can help improve performance by reducing unnecessary updates.

Summary

Custom refs let you create reactive values with custom get/set behavior.

They use track() and trigger() to connect with Vue's reactivity.

Useful for debouncing, validation, or conditional updates.