Spruce is a global state management library for Alpine.js. It allows you to share pieces of data (state) between individual components.
Alpine does not have a core way of sharing state between components. Out of the box, you have a few options:
$dispatch helper to send browser events up the DOM and notify other components of state changes.
Use a global object to hold some state and trick Alpine into re-rendering.
Use a "God" component that holds all of the shared state.
These options have some disadvantages though.
Constantly dispatching browser events can become messy and confusing. You need to keep track of which events are being used on a page and ensure that any changes to those events don't negatively impact other components.
Tricking Alpine into re-rendering can also be risky since all of these APIs are not publically documented and could therefore break in a minor release.
"God" components can negatively impact performance on a site since Alpine walks the entire DOM tree of a component. Adding an
x-data attribute to your
<body> element would mean Alpine needs to walk the entire
<body> elements DOM tree to find directives (or new components).
Spruce provides a single API for sharing state and handles the re-rendering process for you. Thanks to Alpine's "magic properties" API, it can hook directly into Alpine's variable resolution and feels like any other magic property that Alpine provides out of the box, such as