0
0
Vueframework~3 mins

Why Custom refs with customRef in Vue? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your reactive data smarter with just a few lines using customRef!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
let count = 0;
function setCount(val) {
  count = val;
  console.log('Count changed:', count);
}
After
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();
    }
  };
});
What It Enables

You can create reactive values with custom behaviors that automatically run your code when they change, making your app smarter and easier to manage.

Real Life Example

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.

Key Takeaways

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.