Listening to Changes in Exported Props in Svelte

In Svelte, listening to changes in exported props and executing corresponding functions is a common requirement. In this article, we will introduce how to achieve this functionality through reactive declarations and lifecycle hooks.

1. Using $: Reactive Syntax

Svelte’s $: declaration is very powerful, allowing code to automatically run when exported props change. For example, let’s say we have an exported value prop, and we want to execute a function whenever value changes:

1
<script>
2
export let value;
3
4
// Reactive declaration, this block runs when `value` changes
5
$: valueChanged(value);
6
7
function valueChanged(newValue) {
8
console.log('Value changed to:', newValue);
9
}
10
</script>
11
12
<p>{value}</p>

In this example, every time value changes, the valueChanged function will be called and log the new value. This method is straightforward and easy to use, especially for handling simple prop listening scenarios.

2. Using the beforeUpdate Lifecycle Hook

If you need more complex logic control before the component updates, such as triggering a function only when certain conditions are met, you can use the beforeUpdate lifecycle hook. Here’s an implementation example:

1
<script>
2
import { beforeUpdate } from 'svelte';
3
4
export let value;
5
6
let previousValue;
7
8
beforeUpdate(() => {
9
if (previousValue !== value) {
10
valueChanged(value);
11
previousValue = value;
12
}
13
});
14
15
function valueChanged(newValue) {
16
console.log('Value changed to:', newValue);
17
}
18
</script>
19
20
<p>{value}</p>

Here, beforeUpdate runs when the component updates. By comparing the new and old values, we determine whether to call the valueChanged function, which is useful for more controlled scenarios.

When to Use Which Method?

Using $: reactive syntax is suitable for most simple scenarios because it’s concise and responsive, whereas beforeUpdate is more appropriate when you need finer control over the logic flow.