Date:

Mastering Rune Class in Svelte 5

Sharable Rune

We need a sharable Rune class, and of course we must use Context.

import { getContext, hasContext, setContext } from 'svelte';

type RCurrent<TValue> = { current: TValue };

export class Rune<TRune> {
  readonly #key: symbol;

  constructor(name: string) {
    this.#key = Symbol(name);
  }

  exists(): boolean {
    return hasContext(this.#key);
  }

  get(): RCurrent<TRune> {
    return getContext(this.#key);
  }

  init(value: TRune): RCurrent<TRune> {
    const _value = $state({ current: value });
    return setContext(this.#key, _value);
  }

  update(getter: () => TRune): void {
    const context = this.get();
    $effect(() => {
      context.current = getter();
    });
  }
}

Initialize

We must initialize our $state just like anywhere else, only once, in the parent component.

Read Anywhere

We can use it safely in a child component and read the current method.

import { counter } from '$lib/counter.svelte';

const count = counter.get();

Hello from Child: {count.current}

Reactively Update Anywhere

To update a shared $state, we must pass it through a function that can get called.

import { counter } from '$lib/counter.svelte';

let value = $state(8);

counter.update(() => value);

//...

Update Normally

Of course, you can update normally as well.

import { counter } from '$lib/counter.svelte';

const count = counter.get();

count.current = 9;

Conclusion

This article demonstrates how to create a sharable Rune class using Svelte’s Context API. We can use this class to share state between components and update it reactively or normally.

FAQs

Q: What is the purpose of the Rune class?
A: The Rune class is used to create a sharable state that can be accessed and updated by multiple components.

Q: How do I use the Rune class?
A: You can use the Rune class by importing it and creating an instance of it in your component. Then, you can use the methods provided by the class to get, set, and update the state.

Q: Can I use the Rune class with other state management libraries?
A: Yes, you can use the Rune class with other state management libraries, but you may need to modify it to work with your specific library.

Q: Is the Rune class reactive?
A: Yes, the Rune class is reactive, meaning that it will update automatically when the state changes.

Latest stories

Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here