tezvyn:

Explain Svelte Action update and provide a reactive CSS example

AI-drafted, machine-checkedSource: svelte.devadvanced
Explain Svelte Action update and provide a reactive CSS example

Tests Svelte actions beyond initial mount. Strong answers explain update re-runs when parameters change, give a CSS custom properties example, and contrast with destroy. Red flag: suggesting the action re-runs from scratch or using reactive statements.

WHAT THIS TESTS: Whether you understand that a Svelte action is a long-lived lifecycle attachment to a DOM node, not a render-time function. The interviewer wants to see if you know the difference between one-time setup, reactive updates, and teardown, and whether you can implement all three phases correctly without relying on component-level reactivity.

A GOOD ANSWER COVERS: Four things in order. First, the action function itself runs only once when the element is mounted. Second, the update method on the returned ActionReturn object is called immediately after Svelte applies updates to the markup whenever the parameter changes, so you can react to new data without destroying and recreating the node. Third, the destroy method is called when the element is unmounted and should remove event listeners, observers, or timers. Fourth, a concrete example showing node.style.setProperty or similar direct DOM manipulation inside update.

COMMON WRONG ANSWERS: Saying the entire action function re-runs whenever the parameter changes. Trying to use Svelte 5 runes like derived or effect inside the action body to watch parameters, which is an anti-pattern because actions are meant to be imperative DOM utilities outside the component reactivity graph. Returning a new object from update instead of mutating the existing closure state. Forgetting to clean up in destroy after setting global listeners or ResizeObservers.

LIKELY FOLLOW-UPS: How would you type this action using the Action and ActionReturn interfaces from svelte/action? What happens if the parameter changes rapidly, and how would you debounce inside update? How do actions differ from attachments or from bind directives? Can an action return additional custom events or attributes, and how does that affect TypeScript typings?

ONE CONCRETE EXAMPLE: A theme action that receives an object of CSS custom properties. On mount, it writes each property to the node with node.style.setProperty. In update, it receives the new theme object, removes old properties with node.style.removeProperty, then writes the new ones. In destroy, it removes all properties so no inline styles leak after unmount. The component usage looks like use:theme={{primary: color1, spacing: gap}} and when color1 changes, update swaps the CSS variable without remounting the element.

Source: svelte.dev

Read the original → svelte.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.