Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 28 ยท Alpine.js Going Further

Reusable Components, Alpine.data and Stores

Stop repeating inline x-data. Learn Alpine.data for reusable components with parameters, Alpine.store for global state, x-modelable, and the alpine:init event.

Inline x-data="{ ... }" is perfect for small things. But once a component grows to ten lines, or you need the same dropdown in five places, the attribute becomes unreadable and you start copying code. Alpine offers two tools for that: Alpine.data, which defines a named, reusable component, and Alpine.store, which holds global state that every component can read.

You will learn both, how to pass parameters into a reusable component, when to pick a store over a component, how x-modelable lets a component act like an input, and why registration must happen inside the alpine:init event. You should be comfortable with x-data and events.

Registering with alpine:init

Alpine starts itself as soon as its script has loaded. Anything you register must exist before that moment, otherwise x-data="counter" would refer to something that does not exist yet. Alpine fires an alpine:init event on document right before it scans the page, so that is where registrations go.

sequenceDiagram
    participant P as Page
    participant A as Alpine
    P->>A: Script loads (defer)
    A->>P: Fires alpine:init
    P->>A: Alpine.data and Alpine.store calls
    A->>P: Scans the page, starts components

Register data and stores during alpine:init, before Alpine walks the page.

In practice you add a listener in a normal script that runs before the deferred Alpine script has executed:

HTML
<script>
  document.addEventListener('alpine:init', () => {
    Alpine.data('counter', () => ({ count: 0, up() { this.count++; } }));
  });
</script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>

If your registration script comes after the Alpine tag and the page is parsed before Alpine runs, it still works because of defer, but putting it first is the habit that never fails.

Reusable components with Alpine.data

Alpine.data(name, factory) takes a name and a function that returns the same kind of object you would write in x-data. Then any element can say x-data="name" (no braces, no quotes around an object). The object keeps its methods and getters, and this refers to the component data.

A reusable counter

Each x-data="counter" runs the factory again, so the two cards have separate counts. The logic lives in one place, and the markup stays short.

Passing parameters

The factory can take arguments. Call it from the attribute like a function: x-data="counter(10, 5)". This is how server-rendered pages hand initial values to a component.

A component with parameters and init()

A method named init() runs automatically when the component starts, which replaces a long x-init attribute. Use destroy() the same way to clean up when the element is removed.

Global state with Alpine.store

A component's data is private to its element and its children. Sometimes many unrelated parts of the page need the same value: a dark-mode flag, a shopping cart count in the header, a notification list. Alpine.store(name, object) creates one shared reactive object. Read and change it from anywhere with $store.name.

A store shared by two components

Note the bare x-data (no value) on the header and paragraph. Alpine only evaluates expressions inside an element that has an x-data ancestor, so it is the cheapest way to say "this part is an Alpine area".

You can also reach a store from plain JavaScript: Alpine.store('cart').add('Mug'). A store may have an init() method that runs once when the store registers, and a store can be a simple value, such as Alpine.store('darkMode', false).

Components or stores?

Pick the smallest scope

Inline x-data One-off state used in one place.
Alpine.data Same behavior, many independent copies.
Alpine.store One value shared by the whole page.

Start inline and promote only when you need to.

1 / 2

A good question to ask: "If there are two of these on the page, should they share data?" If yes, it is a store. If no, it is a component.

Persistence

State kept in a store lives in memory: reloading the page resets it, and the demos in this track cannot use localStorage anyway because the preview sandbox blocks it. In your own site you can add the official Persist plugin (the $persist magic) to save a value in localStorage. It is shown as a read-only note in Alpine plugins.

Connecting a component to a parent with x-modelable

x-model normally works on form inputs. x-modelable lets any element with x-data behave like an input: it chooses which of its own properties should be the model. The parent then uses x-model on it as if it were a field.

A rating widget that works with x-model

The binding goes both ways: clicking a star updates the parent's score, and the parent's button updates the stars. The widget does not need to know the name score.

Organizing your code

For more than a few components, move registrations into a script file and load it before Alpine. With a bundler, import Alpine, register everything, then call Alpine.start():

JavaScript
import Alpine from 'alpinejs';
import counter from './components/counter';

window.Alpine = Alpine;
Alpine.data('counter', counter);
Alpine.store('cart', { items: [] });
Alpine.start();

In that setup you do not need alpine:init, because you control when start() is called. With the CDN build, alpine:init is the way. Name data components after what they are (dropdown, rating), not where they are used.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why register Alpine.data inside alpine:init?

    Alpine fires alpine:init just before it walks the DOM. A component name used in x-data must already be registered by then.
  2. 2. Two <div x-data="counter"> elements share one registered component. Do they share a count?

    The factory is called once per element. To share data you would use Alpine.store.
  3. 3. How do you read a store named cart in a template?

    Stores are reached through the $store magic. The element also needs an x-data ancestor, even a bare one.
  4. 4. What is x-modelable for?

    x-modelable="prop" marks which property of the component acts as its model.

Summary

  • Register reusable pieces inside document.addEventListener('alpine:init', ...), before Alpine scans the page.
  • Alpine.data('name', (args) => ({ ... })) defines a component; use it with x-data="name(args)". init() and destroy() are lifecycle hooks.
  • Alpine.store('name', {...}) makes global reactive state, read with $store.name. It is kept in memory only unless you add the Persist plugin.
  • x-modelable plus x-model lets a custom component behave like an input.

Next, Alpine plugins and other features.