Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason to use bind with objects or array props in Svelte?

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?

like image 450
JSNinja Avatar asked Aug 30 '25 18:08

JSNinja


1 Answers

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:

  1. If you decide to mutate the object, always bind.
  2. If you just pass it down from parent to child as prop without binding, most likely it's some kind of initial value to child's local state, then you should not mutate it since that would affect parent. Please make a copy before you change.
like image 106
hackape Avatar answered Sep 02 '25 08:09

hackape