javascript / intermediate
Snippet
Shared State via Module Context
The 'context="module"' script runs once per component type, not per instance. It is used to share variables or helper functions across all instances of that component.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
<script context="module">let totalInstances = 0;export const getTotal = () => totalInstances;</script><script>import { onMount } from 'svelte';totalInstances++;onMount(() => {return () => totalInstances--;});</script>
svelte
Breakdown
1
<script context="module">
Defines code that is shared across all instances of this component.
2
totalInstances++;
Increments the shared counter every time a new instance is created.