useVRef
useVRef is a React adaptation of Vue's ref, designed to create reactive states with a .value property.
Basic Type Ref
This scenario is used to store simple values (numbers, strings, booleans). Modifying .value will automatically re-render the component.
const count = useVRef(0);
const name = useVRef('React');
<p>Counter: {count.value}</p>
<p>Name: {name.value}</p>
<button onClick={() => count.value++}>Increment</button>
<button onClick={() => (name.value = `Vureact ${count.value}`)}>Rename</button>The effect of this code is: after clicking the buttons, changes to count.value and name.value are immediately reflected in the interface.
Object Ref
This scenario is used to store an entire object as a ref. You can either modify internal fields of the object or replace the object as a whole.
const user = useVRef({ name: 'Alice', age: 25 });
user.value.age++; // Modify internal field
user.value = { name: 'Bob', age: 30 }; // Replace the entire objectWhen you directly modify user.value.name or user.value.age, the interface updates accordingly.
Shallow Ref
useShallowVRef only tracks the top-level .value property. That is, modifying internal fields does not trigger an update, while replacing the entire value does.
const state = useShallowVRef({ count: 1 });
state.value.count++; // Does not trigger update
state.value = { count: 2 }; // Triggers updateThis pattern is suitable for large object scenarios to reduce the overhead of deep tracking.
API
interface WrapRef<T = unknown> {
value: T;
}
type RefState<T = unknown> = T extends WrapRef<infer U> ? U : WrapRef<T>;
function useVRef<T>(initialValue: T): RefState<T>;
function useShallowVRef<T>(initialValue: T): RefState<T>;Notes
- You still need to explicitly use
.valuein JSX; automatic unwrapping is not supported. useVRefis suitable for normal ref scenarios; useuseShallowVRefonly when you need to track top-level replacements.- Complex structures such as
MapandSetcan also be used as values foruseVRef.
