by have_faith · 3y ago · 0 comments
I like react/jsx precisely because I can use language constructs like filter, map, reduce, etc, instead of a custom implementation of basic things like if statements and loops. I find this much more ergonomic and didn’t realise some people see this as a “workaround”.
Worth also pointing out that when you write these templates, as strings or template literals, they might resemble HTML in appearance but really have no relation to actual HTML except what they output after processing. All of the added directives also have no equivalence in HTML. You’re just writing JS indirectly.
I never really understood those that see this as a weakness and would rather learn a more limited set of template string functions that work kind of like, but not entirely like, the native JavaScript collection functions.
Yes, using a ternary operator in JSX to conditionally render components/values looks a bit ugly, but nothing is stopping you from making a wrapper component like:
<If cond={...}><div>Conditional content</div></If>.
Also with JSX/TSX scopes behave exactly like they do in regular JavaScript, because it is regular JavaScript. Templating languages often invent their own form of scoping mechanism.
I'd suggest avoiding that, since the inner JX expression will be evaluated even if cond is false. In the best case this just means some unnecessary allocations, but in other cases it can cause unexpected errors (e.g. you check obj != null then try to use it inside the if).
Well, actually. it don't have to be. Just React decides to compile JSX in that way.
Vue 3 also supports JSX. But it keep the content of children lazily evaluated.
Their compiler compile a JSX `<Parent><Child /></Parent>` to structure like `h(Parent, {}, { default: () => h(Child, {}, {}) })` . So the child jsx tag is never evaluated unless the Parent component want to.
It's really not a syntax limitation because JSX never specify that the children of element must be eagerly evaluated.
That seems like a dangerous reinterpretation of JSX. It's just a literal syntax, it's not meant to be lazily evaluated.
Having a JSX compiler interpret <Parent><Child /></Parent> as h(Parent, {}, { default: () => h(Child, {}, {}) }) would be like having a JS compiler interpret
let parent = {
child: {}
};
as let parent = {};
Object.defineProperty(parent, 'child', { get: () => ({}) })
That's just... not what that syntax means. It should be h(Parent, {}, [ h(Child, {}, []) ])
Saying 'JSX doesn't specify it' feels like playing a 'there's no rule that says a dog can't play basketball' card. <If cond={...} then={() =>
...
} els={() =>
...
} />
so the `then` and `els` branches only get evaluated if needed{ some_condition ? (
<H2>It was true</H2>
) : ( <H2>It was false</H2>
)Couldn't you put that in a function that returns the correct JSX element or am I misunderstanding the problem? Something like:
renderThing(number) {
if(number > 0) return <div>...</div>
return <div>...</div>
}
const Page = () => {
return <div>{renderThing(someNumber)}</div>
}
Simple ternaries are fine IMO but thats what I do when the logic gets complicated. I never used a nested ternary in that situation, for example.This is because it doesn't get registered as it's own component, so conditionally called children with hooks may cause errors.
So this style of code is fine in react
const items = [];
let runningTotal = 0;
for (const item of someArray) {
runningTotal += item;
items.push(<li>Item {item}; running total {runningTotal}</li>);
}
return (<ul>{items}</ul>);
The closest example I can find in Vue would require a computed property to implement something like this. <script setup>
const items = [1,2,3,4,5,6]
let runningTotal = 0
const getRunningTotal = (item) => {
runningTotal += item
return runningTotal
}
</script>
<template>
<ul>
<li v-for="item in items">
Item {{item}}; running total {{ getRunningTotal(item) }}
</li>
</ul>
</template>
No need for a computed property. Plus, getRunningTotal can be unit tested, or extracted to another file for reusability.If you're after keeping the concerns separate you would need to precompute the running total for each item.
See also: mustache(5) which completely embodies this philosophy.
It is just that above example is so short and readable, that you don't have to bother.
return (
<ul>
{someArray.map((item, idx) => (
<li key={item.id}>Item {item}; running total {idx + 1}</li>
)}
</ul>
);When it comes to comparing React with Vue or Svelte, the templating is not the critical factor.
Ternaries, booleans that cast to JSX, switch statements wrapped in IIFs...
I've done a lot of Vue and your bit of React and overall I prefer the Vue way here.
> Vue uses a templating language closer to default HTML than to JSX, which makes it much easier to write conditionals and loops in template files
Not that you can't with JSX (Solid and Qwik use JSX and have transparent ways of doing optimizations as consumer of those frameworks) but its not currently the default, most (if not all) optimizations must be done "by hand", is a big tradeoff for some places.
The state of the art is less about handling things like loops, and more about reducing the amount of work needed to render static elements. For example, say you have a single component that renders a static table, and in each cell of the table you need to render something dynamic. In the classic vdom system, you'd construct a `table` node, with a `tbody` child, which in turn has `tr` children, which was contain `td` nodes, and then finally in the `td` nodes you render the dynamic content. This works, but most of the content isn't actually changing, only the contents of the `td` nodes. What modern frameworks like Solid and Svelte do is to compile that whole nest of nodes into a single HTML string, and then add instructions that specify where exactly the dynamic content lives. That way, on the initial render, the browser is doing more work natively, and on later updates, only the new content needs to be checked and changed. I know there's a library for React that adds similar capabilities there, albeit with a few more constraints than in other frameworks.
I do know Solid does for-loops differently than in other frameworks, but this is less to do with efficiencies gained by compiling, and more about how to optimally use the signals system that it uses for reactivity. Apart from that, I don't really know of any optimisations that would make something like `v-for` any faster than `.map(...)`.
I did only use `v-for` as an example of sorts though, and in the common case, `v-for` vs a regular `for` loop are similar if not the same, IIRC, but in some cases where your children may show or hide based on downstream data, it can be more efficient