Chapter 6

Advanced Svelte Reactivity

IN THIS CHAPTER

Bullet Using stores

Bullet Creating context

Bullet Creating reactive context

“Context is worth 80 IQ points.”

—ALAN KAY

Passing data down through props or firing events in child components to change data in parent components is a fundamental pattern in any component-based framework. However, not all data needs to be — or should be — in the component hierarchy. In this chapter, you'll learn how to provide data to multiple components by using Svelte stores and Svelte context.

Constructing and Stocking the Store

A store in Svelte is an object with a subscribe() method that allows components to be notified when the store's value changes. A store can be writable, meaning that its value can be both read and changed from outside the store, or readable, meaning that its value can be changed only from within.

Creating a writable store

Since they don't produce any output to the DOM, stores can be created in normal JavaScript modules. To create a writable store, import the writable() method from svelte/store and then assign the result of calling writable() to a variable or constant and export it.

The writable() method takes one required argument, which will ...

Get JavaScript All-in-One For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.