Aside from the breaking changes listed on the previous page, Svelte 5 should be a drop-in replacement for Svelte 4. That said, there are some features that we will remove in a future major version of Svelte, and we encourage you to update your apps now to avoid breaking changes in future.
beforeUpdate and afterUpdatepermalink
beforeUpdate(fn)
schedules the fn
callback to run immediately before any changes happen inside the current component. afterUpdate(fn)
schedules it to run after any changes have taken effect.
These functions run indiscriminately when anything changes. By using $effect.pre
and $effect
instead, we can ensure that work only happens when the things we care about have changed. The difference is visible in this example — with afterUpdate
, the callback runs on every mousemove
event, whereas with $effect
, the function only runs when temperature
changes:
<script>
import { afterUpdate } from 'svelte';
let coords = $state({ x: 0, y: 0 });
let temperature = $state(50);
let trend = $state('...');
let prev = temperature;
afterUpdate(() => {
console.log('running afterUpdate');
$effect(() => {
console.log('running $effect');
if (temperature !== prev) {
trend = temperature > prev ? 'getting warmer' : 'getting cooler';
prev = temperature;
}
});
</script>
<svelte:window on:mousemove={(e) => coords = { x: e.clientX, y: e.clientY } } />
<input type="range" bind:value={temperature} >
<p>{trend}</p>
Note that using $effect
and $effect.pre
will put you in runes mode — be sure to update your props and state accordingly.