by nailer · 1y ago · 0 comments
const [name, setName] = useState('blastonico')
...
setName('nailer')
You do: let name = 'blastonico'
...
name = 'nailer'
Also a single .svelte file includes everything you need for a component (HTML, JS, CSS), so it's easier to manage.I get that assigning variables is easier to understand, but it's way, way harder to actually scale and maintain. Check out flux architecture.
We’re not just assigning variables directly, current JavaScript frameworks use a compiler.
const [state, setState] = useState(0)
const func = () => {
console.log(state) // 0
setState(40)
console.log(state) // 0
} [foo, setFoo] = useState(1);
[bar, setBar] = useState();
setFoo(10);
setBar(foo * 2); // Is bar 2 or 20 at this point?Let's say you instead did the `setFoo` and `setBar` in a click handler. In that case, when you click the button it would tell React "Hey, in the next render set `foo = 10` and `bar = 2` (since `foo = 1)`. Then React goes ahead and runs your function again, and `foo` and `bar` will both be updated.
The value of `foo` does not change within a render cycle, you literally don't have to worry about state.
It might seem that there’s a chance that people will be confused about what bar is, but in practice all the changes are happening in handlers and bar will be a const anyway so you have no plans to mutate it directly.
Just a follow up. If foo and bar are expected to be constant in the rendering code, what's the point of the setXXX() functions? Why not just make them constant explicitly and say mutating them elsewhere like in the handlers/controllers?
So there will be 3 cycles?
1: foo = 1, next(foo = 10)
bar = undef, next(bar = 2)
2: foo = 10
bar = 2, next(bar = 20)
3: foo = 10
bar = 20
Does the above sound right?It just feels a bit weird that there's special .svelte specific rules.
Runes kinda fix this, but it's still a bit weird.
I think Solid or Vue are much simpler (but only did small projects in them) and have a simpler mental model. I've not yet used Preact, but heard good things about it