Skip to content

Instantly share code, notes, and snippets.

@vdsabev
Last active October 15, 2023 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdsabev/49b3ab2daf33f2ae125c9e6e8f56a534 to your computer and use it in GitHub Desktop.
Save vdsabev/49b3ab2daf33f2ae125c9e6e8f56a534 to your computer and use it in GitHub Desktop.
Vue's `reactive` in React
const useReactive = (object, dependencies = []) => {
const [_, setState] = useState(0);
return useMemo(
() => toReactive(object, () => setState((state) => state + 1)),
dependencies
);
};
const toReactive = (object, callback) => {
if (!object || typeof object !== 'object') return object;
const array = (Array.isArray(object) ? object : [object]).map((item) => {
const proxy = {};
Object.keys(item).forEach((key) => {
let value = toReactive(item[key], callback);
Object.defineProperty(proxy, key, {
enumerable: true,
get() {
return value;
},
set(v) {
value = toReactive(v);
callback(value);
},
});
});
return proxy;
});
return Array.isArray(object) ? array : array[0];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment