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

Viewed 636

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?

2 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.

app.svelte


<script>
    import Component from './component.svelte'  
    let prop = 'test'
</script>
<div>
    From host: <strong>{prop}</strong>
</div>

<div>
    <h2>First: binded</h2>
    <Component bind:prop />
</div>

<div>
    <h2>Second: not binded</h2>
    <Component {prop} />
</div>

component.svelte

<script>
    export let prop
</script>

From component: {prop}
<input bind:value={prop} />

https://svelte.dev/repl/0e7bdfb4c5e14cdea306cf6f7e20ee5e?version=3.44.1

The second component does not change the value of the host

Related