tezvyn:

Bind an input to a variable and validate with reactivity

AI-drafted, machine-checkedSource: svelte.devbeginner
Bind an input to a variable and validate with reactivity

Tests Svelte reactivity: connecting DOM state to validation logic. Good answer: `$state` for the variable, `$effect` to run validation when it changes, cleanup if needed. Red flag: using effects where event handlers suffice or creating infinite loops.

WHAT THIS TESTS: This question tests whether you understand Svelte's reactivity model at a semantic level, specifically how state changes propagate through effects. The interviewer wants to see that you know reactive state must be explicitly declared and that side effects should be isolated inside effect runes.

A GOOD ANSWER COVERS: First, declare the input value as reactive state using the state rune. This creates a variable that the framework tracks. Second, create an effect that reads this state variable. Because effects re-run whenever any state they read changes, placing your validation logic inside the effect guarantees it executes after every update. Third, if your validation sets up persistent resources like timers or network requests, return a cleanup function from the effect. Svelte calls this cleanup immediately before the effect re-runs and when the component destroys. Fourth, mention that effects do not run during server-side rendering, so validation that must happen universally may need a different trigger.

COMMON WRONG ANSWERS: A major red flag is using effect for logic that belongs in an event handler. The Svelte docs explicitly call effect an escape hatch and prefer event handlers when possible. Another red flag is creating infinite loops by writing to the same $state variable inside an effect that reads it without guards. Also, forgetting cleanup when using intervals or subscriptions inside an effect shows you do not understand the lifecycle contract.

LIKELY FOLLOW-UPS: The interviewer may ask how you would debounce validation. You would store a timer ID in the effect and return a cleanup that clears it. They may also ask about derived state versus effects; validation results that feed directly into the template should use derived state, while side effects like logging or API calls belong in effects. They might also ask what happens if the effect reads no state; the answer is it runs only once on mount.

ONE CONCRETE EXAMPLE: Imagine an email input. You write let email = state('') and an effect(() => { const valid = email.includes('@'); console.log(valid); }). Every keystroke updates email, which causes the effect to re-run and log the new validity. If you had instead used setInterval inside the effect to poll the value, you would return () => clearInterval(id) so old intervals do not accumulate.

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.