@lwc/state
v0.25.2
Published
State Management using Signals
Downloads
291
Maintainers
Keywords
Readme
@lwc/state
A state management solution for Lightning Web Components (LWC) using signals. This package provides utilities for creating and managing reactive state, computed values, and context within LWC applications.
Features
- 🔄 Reactive State Management - Create and manage reactive state using signals
- 🧮 Computed Values - Define derived state that automatically updates when dependencies change
- 🌳 Context System - Share state across component trees with provider/consumer pattern
- 🔒 Type Safety - Built with TypeScript for robust type checking
- ⚡ Performance - Efficient updates with microtask-based batching
Installation
To install the library, use npm or yarn:
npm install @lwc/state
yarn add @lwc/stateAPI Reference
defineState
The main function for creating state definitions. It accepts a callback function whose first parameter is an object that exposes API utilities for creating state, followed by any manner of parameters to be used in order to initialize a state manager instance when the state factory function is called.
The exposed API utilities are:
atom<T>(initialValue: T): Creates a reactive atomic valuecomputed(signals: Signal[], computeFn<T>: (...signalValues: unknown[]) => T): Creates a derived value based on provided signals arraysetAtom<T>(signal: Signal<T>, newValue: T | Signal<T>): Directly sets the value of an atom signal. Calling withnewValueof typeSignalwill result insignaltracking and maintaining the same value asnewValue. Ifsignalis tracking anotherSignaland is called with non-Signalvalue, onlysignalwill be updated and tracking will cease. Can only be used to modify atoms that were created within the same state manager instance. Attempting to modify atoms from other state managers will:- In development: Throw a ReferenceError
- In production: Silently fail without modifying the atom
fromContext
This function is the mechanism to use in order to consume state manager context from parent components. In order to make the context available, the parent MUST do the following:
- create the state manager instance BEFORE the component is connected
- set the state manager instance to an enumerable property
Usage
Basic State Management
Create a state definition using defineState:
import { defineState } from '@lwc/state';
const useCounter = defineState(
({ atom, computed, setAtom }, initialValue = 0) => {
// Create reactive atom
const count = atom(initialValue);
// Create computed value
const doubleCount = computed([count], (countValue) => countValue * 2);
// Create a function that directly sets the count atom
const increment = () => {
setAtom(count, count.value + 1);
};
// Create a function that directly sets the count atom
const setCount = (newValue: number) => {
setAtom(count, newValue);
};
return {
count,
doubleCount,
increment,
setCount,
};
}
);Using State in Components
To use the useCounter state definition in your LWC.
import { LightningElement } from 'lwc';
import useCounter from '../xyz';
export default class extends LightningElement {
counter = useCounter();
}<template>
Counter: {counter.value.count}
</template>Context System
Share state across your component tree:
// state-manager.ts
export const themeStateManager = defineState(
({ atom }, initialValue = 'light') => {
// Create reactive state
const theme = atom(initialValue);
return {
theme
};
}
);To provide and consume context in your components, use the fromContext api to consume a parent's state manager(s):
// parentComponent.ts
import { api, LightningElement } from 'lwc';
import themeStateManager from './state-manager';
export default class ParentComponent extends LightningElement {
@api stateManager = themeStateManager()
}A child component may access a parent's state manager via fromContext():
// childComponent.ts
import { api, LightningElement } from 'lwc';
import { fromContext } from '@lwc/state';
import themeStateManager from './state-manager';
export default class ChildComponent extends LightningElement {
@api parentStateManager = fromContext(themeStateManager);
}Enable Experimental Signals
To use reactive updates in your templates, you need to enable the experimental signals feature flag in your LWC configuration.
History
The initial contents of this repo were copied from
commit 8336701 of the @lwc/state package in the lightning-labs repo.
Refer to that repo for earlier history of this package.
