Introducing useWatchFields: A Vue 3 Custom Hook for Efficient Field Watching
This article presents the Vue 3 custom hook useWatchFields, which lets developers monitor specific fields of a large reactive state object with flexible, lightweight, and optionally debounced change detection, simplifying code compared to traditional watch and computed APIs.
In Vue 3 development, managing large reactive state objects often requires watching specific fields, which can be cumbersome with the standard watch and computed APIs.
To simplify this, a new custom hook useWatchFields is introduced. It allows developers to specify an array of field names to monitor, automatically tracking changes and providing previous and new values without external libraries, using only Vue's built‑in API.
Why useWatchFields?
When only a subset of fields matters, setting up individual watches leads to verbose and inflexible code. useWatchFields precisely watches the designated fields and passes change details to a callback.
How to use
Given a state object with fields such as name and age , the hook can be used as follows:
import { ref } from 'vue'
import { useWatchFields } from './useWatchFields'
const state = ref({
name: 'John Doe',
age: 30,
email: '[email protected]',
})
// Watch name and age
const { onChange } = useWatchFields(state, ['name', 'age'])
onChange((data) => {
console.log('Changed fields:', data.changedFields) // ['name', 'age']
console.log('Field change map:', data.fieldChangeMap)
})The hook also supports debouncing and immediate execution options.
Core Features
Flexible field specification – simply pass an array of field names.
Efficient event triggering – uses a manual ref to manage listeners, keeping the mechanism lightweight.
Detailed change information – returns changed fields, the full list of watched fields, and a map of old and new values.
Optional debounce – prevent excessive triggers by setting debounceTimeout in milliseconds.
Example with debounce:
const { onChange } = useWatchFields(state, ['name', 'age'], { debounceTimeout: 500 })Applicable Scenarios
Form handling – watch only relevant input fields.
Dynamic data updates – such as user profiles or shopping cart state.
Conditional rendering – trigger view updates based on specific field changes.
Overall, useWatchFields offers a concise, lightweight solution for field‑level reactivity in Vue applications.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.