Rich Harris has a nicer solution
You can use use:action
:
Actions are functions that are called when an element is created.
For example:
<script>
let tasks = [];
function addTask() {
tasks = [...tasks, { title: "" }];
}
function init(el){
el.focus()
}
</script>
{#each tasks as task}
<input type="text" bind:value={task.title} use:init />
{/each}
<button on:click={addTask}>Add task</button>