Perform Action Before State Change in Svelte

- 1 minute read

Sometimes we might want to intercept state changes in Svelte and perform an action just before they happen.

To do this, you can use Svelte’s beforeUpdate function.

The below snippet is a simple example implementation of beforeUpdate:

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

    let num = 0;

    beforeUpdate(() => console.log(`num is about to increase!`);
</script>

<p>Clicks: {num}</p>

<button on:click={() => num++}>Increment</button>

When the button is clicked, the num variable will increase reactively.

However, "num is about to increase!" will be logged to the console each time the button is clicked - but before num is increased.

Link to this section Conclusion

Thanks for reading!

And in case you were wondering, there is also an afterUpdate function which exhibits the same behavior as beforeUpdate, except that it runs after each state change.