Define a State Manager

Use the defineState function to define a state manager. State management relies on extensive infrastructure within the LWC Framework. The defineState function makes it straightforward to ensure that all connections are made correctly.

There are two aspects of using defineState to create a state manager. The first is the specific JavaScript syntax that you use to define a state manager with defineState. The syntax uses a few advanced JavaScript features. Using defineState to define a state manager might feel awkward at first, but this syntax is what makes state managers self-contained, and isolated from other instances of the same or other state managers.

The second is the internal implementation of your state manager, in the form of an anonymous function. This function is used to create instances of your state manager, and also defines the API your state manager provides to other LWC components. Specifically, you must understand:

  • How to use the state management primitives atom, computed, and setAtom to define the properties and actions of your state manager.
  • How to expose the properties and actions your state manager provides (its API).

Learn the outer syntax first, in Syntax Introduction: A Simple Counter. The example is deceptively short and simple. A thorough explanation covers the concepts of the syntax that you must understand.

Then learn how to build your state manager's implementation using the state management primitives, in Implement a State Manager. The example used is an expanded version of the counter state manager used in Syntax Introduction: A Simple Counter. While still simple, it illustrates all three state manager implementation functions, and how to interact with the state manager from a component's user interface.

Share a State Manager Across Components illustrates how many components can access and interact with a shared state manager. The example is, once again, a counter manager, but refactored into multiple separate user interface components. This example also uses the best practice of putting the state manager into a standalone API module component.

Finally, look at the examples published externally, and in Nested State Manager Example. That example is longer, and shows off additional features of LWC state management, including using nested state managers as an alternative to using @wire or other UI API calls.