3 ms·
I love using hooks because you can write extremely terse code, but the magical rules are almost not even worth it. Hooks are not robust to reactive code pattern
by anonytrary 6y ago
I love using hooks because you can write extremely terse code, but the magical rules are almost not even worth it. Hooks are not robust to reactive code patterns. There's no reason why hooks couldn't have been implemented as a dynamic graph that forgets/learns which render calls have been subscribed to the current computation graph. Overall, it's a poor design, but it is very expressive if you know what you are doing. For example, a typical reactive function would be able to handle conditional reactive dependencies:
const myReactiveComputation = () => {
if (getReactiveValue() > 5){
console.log(getOtherReactiveValue());
}
}
When getReactiveValue() returns something <= 5, the reactive computation should automatically unsubscribe from getOtherReactiveValue, since that value changing no longer as any implications on the result of the reactive computation. Once getReactiveValue() changes to something > 5, the computation re-subscribes to getOtherReactiveValue. It's not hard to implement this if you're modeling your computation graph correctly. Unfortunately, hooks was implemented to depend on call-order, which makes absolutely no sense. This leads to actually more verbose constructs such as:
useEffect(() => {
if (iWantToRunThis(){
...
};
}, [])
This is better expressed as:
if (iWantToRunThis()) useEffect(() => {...}, []);
But alas, this is prohibited by hooks because of how they were implemented.
- postalrat 6y agoYou could also do {iWantToRunThis && <ComponentUsesEffect...
- anonytrary 6y agoI've seen a lot of people using this strategy -- creating a null component that just runs an effect. It works and is totally valid, but IMO increases the API surface area unnecessarily. It should work without resorting to this "hack".
- amoerie 6y agoWhat you are describing is exactly how mobX works, if I'm not mistaken.
- anonytrary 6y agoYep, it's how a lot of DAG computation libraries work.