Discover how to make your reactive data smarter with just a few lines using customRef!
Why Custom refs with customRef in Vue? - Purpose & Use Cases
Imagine you want to track a value that changes over time and also run some extra code whenever it updates, but you have to do all this manually by watching and updating variables everywhere.
Manually tracking changes and running extra logic is messy and repetitive. It's easy to forget to update something or write buggy code that's hard to maintain.
Using customRef in Vue lets you create special reactive references that run your custom code automatically when the value changes, keeping your code clean and reliable.
let count = 0; function setCount(val) { count = val; console.log('Count changed:', count); }
import { customRef } from 'vue'; const count = customRef((track, trigger) => { let value = 0; return { get() { track(); return value; }, set(val) { value = val; console.log('Count changed:', value); trigger(); } }; });
You can create reactive values with custom behaviors that automatically run your code when they change, making your app smarter and easier to manage.
Think of a form input where you want to validate the input live and show messages only when the user stops typing for a moment. customRef helps you build this debounce behavior easily.
Manual tracking of reactive values is error-prone and repetitive.
customRef lets you add custom logic to reactive references.
This makes your Vue apps cleaner, smarter, and easier to maintain.