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: 1743670205019
Datetime: Thu Apr 03 2025 08:50:05 GMT+0000 (Coordinated Universal Time)
Now: 1743670205019
Datetime: Thu Apr 03 2025 08:50:05 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()))