Svelte logo

Svelte by Example: Modules

JavaScript modules let us share code between components. In a .svelte.js file, we can use runes to share reactive state too.

In this example, we'll move our todo state into a reusable function.

Export a factory function to create a separate list each time it's called.

Return the reactive object. Components can read and update its properties just like local state.

todos.svelte.js
export function createTodos() {
  const list = $state({
    todos: [{ task: 'Walk dog', completed: false }],
  });

  return list;
}

Import the factory like any other JavaScript function.

Create the state inside the component. Each instance gets its own list, which can be shared with descendants through context.

TodoList.svelte
<script>
  import { createTodos } from './todos.svelte.js';



  const list = createTodos();
</script>

{#each list.todos as todo}
  <p>{todo.task}</p>
{/each}

<button onclick={() => list.todos.push({
  task: 'Read newspaper', completed: false,
})}>Add a todo</button>

Don't put per-user state in a shared module-level object when rendering on the server. Modules can be shared between requests, so one user's todos could become another user's todos. A factory keeps the state separate.