by paulddraper · 3y ago · 0 comments
I'll draw an analogy.
---
Why did async/await replace callbacks? They are really the same thing, aren't they? Aren't callbacks good enough?
Async/await allowed programmers to write asynchronous code as if it were synchronous.
---
Why did hooks replace classes/imperative? They are really the same thing, aren't they? Aren't classes/imperative good enough?
Hooks allowed programmers to write stateful code as if it were stateless.
function MyComponent() {
const [value, setValue] = useState(false);
const buttonClass = value ? "on" : "off";
return (
<button
className={buttonClass}
onClick={() => setValue(!value)}
>
{String(value)}
</button>
);
}
This is functional code, without scary, hard-to-reason side-effects. Except for one limited part, which operates in a stateful way.I argue that this is simpler than the equivalent imperative-DOM modification code, and the gap between these only increases with real programs.
This isn't just a weird "web bro" thing; the hooks paradigm is useful (in theory and practice) to every UI platform.
I even wrote an implementation (closed source) for hooks in Angular. It was lovely.
It is some pseudo DSL with hidden hard to reason mutable state.
let result;
for (const item of items) {
result = await foo(item);
if (result) {
break;
}
}
is not synchronous code. But you can write it very close to the mental model of synchronous programming.The same is true of hooks. The code is not stateless, but you can write it very close to the mental model of stateless programming.
That is why -- despite them being optional -- hooks have become incredibly popular.
It also shows that although there might be some learning investment required to use the more modern version of both, it's well worth the effort. I can't imagine going back to callback-riddled javascript