useContext
Reactive Context API
Wrapper for setContext
and getContext
. Always returns reactive Writable<T>
across nested components.
Usage #
// Parent
import { useContext } from 'sveltuse'
const time = useContext('time', new Date())
// Child One
const time = useContext<Date>('time')
// Another nested child
const time = useContext<Date>('time')
Example #
Now: 1735184787437
Datetime: Thu Dec 26 2024 03:46:27 GMT+0000 (Coordinated Universal Time)
Now: 1735184787437
Datetime: Thu Dec 26 2024 03:46:27 GMT+0000 (Coordinated Universal Time)
- Svelte
<script lang="ts">
import { Button } from 'flowbite-svelte'
import { useContext } from 'sveltuse'
const time = useContext<Date>('time')
</script>
<div>
<div class="text-left">
<div>Now: {$time.getTime()}</div>
<div>Datetime: {$time}</div>
</div>
<div class="mt-4">
<Button on:click={() => time.set(new Date())}>Click me</Button>
</div>
</div>
Advanced #
Note: All of the below examples will return exactly same Writable<Date>
.
useContext('time', new Date())
// useContext('time', () => new Date())
// useContext('time', readable(new Date()))
// useContext('time', writable(new Date()))
// useContext('time', () => readable(new Date()))
// useContext('time', () => writable(new Date()))