I noticed that if an object or array is passed in as a prop, then when any element inside is changed in the child component, the change is reflected in the original object or array in the parent component. It seems like 2-way binding is already happening. Is there any reason then to use bind with objects or arrays? Does it make any difference?
Yes there's a difference.
Roughly speaking, view reactivity in svelte is solely decided by some sort of assign operation (tracing the =
operator). bind
would be transpiled into assign in the parent's scope. Without it, parent wouldn't be notified of change.
This behavior could be compared to react's setState
call, which is also the sole thing that can trigger reactive update.
In both svelte and react, same behavior can be reproduced: you pass an object down as prop, you can mutate it in child component, render only in child component without notifying parent to update. It's just not recommended to do so.
I don't have strong opinion about mutable data, but it's generally an anti-pattern to write any code that produces inconsistency between view and state.
My rule of thumb:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With