Fred Hors
Fred Hors

Reputation: 4156

Why is this object changed from binded component?

I have this simple situation in my Svelte project:

REPL: https://svelte.dev/repl/41112edc53e04d59ba9a824cc9e6cde3?version=3.48.0

<script>
    import Comp from "./Comp.svelte";
    
    let obj = {hello: 'world'};
    
    $: console.log("obj in App:", obj)
</script>

<Comp bind:obj></Comp>
<script>
    export let obj;
</script>

<h1>Hello {obj.hello}!</h1>

What I don't understand is why the obj in App.svelte is changed from the Comp.svelte the first time it renders.

You can see in the log:

image

I expect it not to be changed until I change it somehow.

Upvotes: 1

Views: 79

Answers (1)

brunnerh
brunnerh

Reputation: 185410

I think the logic is like this:

  • Setting the obj property of <Comp> causes the property to be invalidated there
  • Because the value is bound via bind:obj, an invalidation of the property causes an invalidation in <App> as well.
  • The reactive statement is triggered again by this invalidation

If you use <Comp {obj} /> instead, this does not happen.

In general I would not recommend relying on the precise number of times that reactive statements are called.

Upvotes: 4

Related Questions