Skip to Content
DocsRecipesShare state between frontend modules

Sharing state between frontend modules

In general, state in React apps should be managed using React . Use the useState hook (or useReducer) and Context  to pass state around within your frontend module.

In some cases, you may need to manage state outside React, such as when you have separate React applications that need to share state. This can come up, for example, if your frontend module has multiple extensions that need to share state with each other.

In these cases you can use the @openmrs/esm-state features of @openmrs/esm-framework. The framework provides functions for managing state using Zustand .

Usage

A Zustand store can be created using createGlobalStore:

import { createGlobalStore } from "@openmrs/esm-framework"; export interface BooksStore { books: Array<string>; } export const bookStore = createGlobalStore<BooksStore>("books", { books: [], });

The store can then be accessed using getGlobalStore

import { getGlobalStore, subscribeTo } from "@openmrs/esm-framework"; const bookStore = getGlobalStore<BooksStore>("books"); console.log(bookStore.getState()); subscribeTo(bookStore, (state) => state.books, (books) => console.log(books)); bookStore.setState({ books: ["Pathologies of Power"] });

In React:

import React from "react"; import { getGlobalStore, useStore } from "@openmrs/esm-framework"; const bookStore = getGlobalStore<BooksStore>("books"); function BookShelf() { const { books } = useStore(bookStore); return <>{books.join(",")}</>; }

There are a few other ways that you can use stores in React, such as by creating a subscription in a useEffect block, or by using Provider and connect, but this method is by far the simplest.

Other notes

If your directory structure allows, you can also pass stores around explicitly:

bookStore.ts
import { createGlobalStore } from "@openmrs/esm-framework"; export interface BooksStore { books: Array<string>; } export const bookStore = createGlobalStore<BooksStore>("books", { books: [], });
import { bookStore } from "./bookStore"; bookStore.setState({ books: ["A History of Global Health"] });

Global stores are in memory by default. If a store needs to survive a browser refresh within the same tab session, pass "sessionStorage" as the third argument to createGlobalStore(). The framework currently supports in-memory stores and session-storage-backed stores.

See the Zustand docs  for more information about stores.

Last updated on