As I was increasingly upset with the lack of variable highlighting in Volar, I started doing some React experiments.
In particular, I found the useEffects hook API very annoying, because it fails to communicate the intent of what you’re trying to accomplish.
So, I order to mitigate this, I wrote a few wrappers:
import {DependencyList, useEffect} from 'react';
function onMount(fun: () => void) {
useEffect(() => { fun(); }, []);
}
function onUmnount(fun: () => void) {
useEffect(() => {
return () => { fun(); };
}, []);
}
function onMutate(dep: DependencyList, fun: () => void) {
useEffect(() => { fun(); }, dep);
}
As far as I could test, they work really well, with the advantage that you can pass async functions to them:
function Foo() {
const [name, setName] = useState('');
onMount(async () => {
console.log('hello async');
});
onUmnount(() => {
console.log('unmounted');
});
onMutate([name], () => {
console.log('updated', name);
});
return <div>Hello {name}</div>;
}
I’m somewhat tempted to create a library for this. And maybe other high-order wrappers.
No comments:
Post a Comment