Hacks & Internals

Valtio exposes some of its internal mechanisms for advanced use cases or library development. These APIs are considered unstable and may change without notice. Use them at your own risk.


getVersion

In Valtio, updates to proxied objects are tracked internally with a version number. Every mutation increments a global version number and assigns it to the mutated proxy and its ancestors. This is how snapshot and useSnapshot efficiently determine if a new snapshot is needed.

The getVersion function allows you to read this internal version number for a given proxy.

Signature:

getVersion(proxyObject: object): number | undefined

Usage:

import { proxy, getVersion } from 'valtio/vanilla';

const state = proxy({ count: 0 });
const version1 = getVersion(state);

state.count++;

const version2 = getVersion(state);

console.log(version1 !== version2); // true, because the state was mutated.

This is not typically useful in application code, as Valtio's public API handles version tracking automatically.


unstable_getInternalStates

This function exposes Valtio's internal state maps and sets. Modifying these can lead to unpredictable behavior and is strongly discouraged unless you have a deep understanding of the source code.

Exposed Internals:

  • proxyStateMap: A WeakMap linking proxy objects to their internal state.
  • refSet: A WeakSet of objects marked with ref().
  • snapCache: A WeakMap for caching snapshots.
  • versionHolder: An array holding the current global version number.
  • proxyCache: A WeakMap to cache created proxies.

unstable_replaceInternalFunction

This function allows you to replace some of Valtio's internal functions. This is an extremely advanced feature intended for patching or extending Valtio's core behavior, for example, in a testing environment or for library integration. Incorrect use can easily break Valtio.

Example:

import { unstable_replaceInternalFunction } from 'valtio/vanilla';

unstable_replaceInternalFunction('canProxy', (originalCanProxy) => {
  return (value) => {
    // Custom logic to decide if an object can be proxied
    return originalCanProxy(value);
  };
});