3 ms·
React extended JavaScript syntax with JSX to make it easier to create elements. Why not do the same for hooks? It's clear that the existing rules are confusing
by pavlov 2y ago
React extended JavaScript syntax with JSX to make it easier to create elements. Why not do the same for hooks?
It's clear that the existing rules are confusing: hooks look like functions but follow special rules, you need to manually manage hook dependencies with crutches like useCallback / useMemo, etc.
Just adding a few keywords like "hook" and "use" could make it clearer and allow the build tool to automatically generate some of the boilerplate like useCallback.
The example in the article might look something like this (leaving out the TypeScript annotations):
hook boolean(initialValue) {
use [value, setValue] from hook state(initialValue);
return [
value, {
setFalse: () => setValue(false),
setTrue: () => setValue(true),
toggle: () => setValue(!value)
}
];
}
Behind the scenes this would generate a useBoolean() hook that can be called directly from plain JS if needed, just like JSX generates createElement() calls.
- rpastuszak 2y agoAt this stage, I think it’s more likely that React will rely on its compiler to support a less annoying but still JavaScript syntax for hooks, signals etc…
- pavlov 2y agoBut if you’re using a compiler to support a syntax that looks like plain JavaScript but actually has different semantics, that seems objectively worse than adding a few keywords. IMO that was a major lesson from C++ — it wasn’t all that clever to allow code that looks like C and would pass a C compiler but does something completely else.
- jitl 2y agoThe compiler looks like JavaScript and behaves like JavaScript but it’s optimized; to me asking for React to add more random non-JS keywords to their compiler JS syntax is like asking that you add more keywords to C functions to allow you to build with -O3
- pavlov 2y agoCorrect use of hooks isn’t an optimization, it’s a necessity to make your programs work. Your position is more like saying: “Why does C++ need special syntax for initializers? Surely you can just use alloca() to grab a variable-sized blob of bytes from the stack and cast it to whatever types you’re initializing.”
- CharlieDigital 2y agoVue has done this with macros generally focused on reducing boilerplate and improving DX. The `defineModel` macro from release 3.4[0] is a prime example where a really simple macro completely changes my workflow and makes refactoring complex components a breeze. [0] https://chrlschn.dev/blog/2024/01/a-conceptual-model-of-state-in-vue-34-using-definemodel/ https://chrlschn.dev/blog/2024/01/a-conceptual-model-of-stat...