Skip to content

Instantly share code, notes, and snippets.

@joemaffei
Created November 8, 2022 06:04
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 joemaffei/aa45f6c615659bfd394e84953747ea5c to your computer and use it in GitHub Desktop.
Save joemaffei/aa45f6c615659bfd394e84953747ea5c to your computer and use it in GitHub Desktop.
Simple mutable state in React using Proxy
import * as React from 'react';
function useProxy<T>(initialValue: T) {
const [state, setState] = React.useState(initialValue);
const proxy = React.useMemo(() => {
return new Proxy(
{ value: state },
{
set(obj, prop, value) {
if (prop === 'value') {
setState(value);
obj.value = value;
return true;
}
},
}
);
}, []);
return proxy;
}
export default function App() {
const count = useProxy(0);
return (
<div>
<h1>Count: {count.value}</h1>
<button onClick={() => count.value++}>Add 1</button>
<button onClick={() => count.value--}>Subtract 1</button>
<button onClick={() => (count.value = 0)}>Reset to 0</button>
<button onClick={() => (count.nuke = 'boom')}>BREAK EVERYTHING</button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment