1

When the lifecycle function(lets say afterUpdate()) in a Svelte component gets invoked. Does it cause the component to rerender?

For example

<script>
    import { afterUpdate } from 'svelte';

    afterUpdate(() => {
        console.log('the component just updated');
    });
</script>

Is this simply just a component updating or does rerendering occur?

Ming
  • 21
  • 3

1 Answers1

0

The afterUpdate function executes a callback after the component get updated: https://svelte.dev/docs#run-time-svelte-afterupdate

Is this simply just a component updating or does rerendering occur?

It simply lets you do something after an update occurred. Of course, you can update properties and it will rerender the component, but Svelte will manage everything for you so you have to worry about an infinite update loop:

For example, here the method afterUpdate will be called only twice:

  1. on mount
  2. when name change due to the setTimeout
<script>
    import {afterUpdate} from 'svelte';
    let name = 'world';  
    let counter = 0;

    afterUpdate(() => name = `${name} ${counter++}`)
    
    setTimeout(() => name= 'everybody', 1000)
</script>

<h1>Hello {name}!</h1>
krampstudio
  • 3,519
  • 2
  • 43
  • 63