Storing values
There are several forms of storage available in modern browsers. Here is a break-down of them and when they should be preferred.
In-Memory
In general, in memory storage refers to anything stored in Javascript that is not part of a persistent storage. In general, values stored in memory remain valid for:
Type | Duration |
---|---|
Variable | Variable scope |
React State | Component's lifecycle |
React Memo | Component's lifecycle |
React Context | React subtree lifecycle |
Global Store | Until page reload |
No in-memory values survive page reload. For values that need to persist across a page-reload (and note that this means browser page refresh and not merely in-application navigation), use persistent storage.
Variables
Simplest way to store a value. Looks something like:
const value = /* some value */;
The lifecycle of this variable depends on it's scope (opens in a new tab). In general, it's preferable to store values in the narrowest scope possible, that is, prefer function-scope to module-scope and module-scope to global-scope.
Inside React, it is generally preferrable to use simple variables unless recomputing the variable is expensive. For example:
const name = `${patient.first} ${patient.last}`;
Is likely to be fine, unless operating on a large list of items or performing potentially complicated operations.
React State
const [value, setValue] = useState(/* some value */);
Sometimes we need variables which maintain consistent values across component renders. Where these values are component-specific, useState()
allows us to store a component-specific version of a value that only gets updated when it's setter is called.
React Memo
const value = useMemo(() => /* some computation */, [dependencies]);
Not exactly "storage", but like useState()
provides a consistent value until a condition holds (a value in the dependency array changes). Useful for infrequently computed or expensive to compute state.
React Context
React's Context mechanism can be useful for storing data that needs to be shared solely by components in the same React tree; for example, values that are shared by multiple components in the same microfrontend might benefit from using React's context. React Context provides values with a scope beyond just the lifecycle of a single component, but which are not maintained in the absence of the React tree. For example, a form might use React Context to store all the "current" values of all the input components on the form.
// in a parent module
const MyContext = createContext(/* some value */);
// inside a parent component
return (
<MyContext.Provider value={/* some value */}>{children}</MyContext.Provider>
);
// inside a child component
const myValue = useContext(MyContext);
This is useful for ensuring that an entire React tree has a consistent version of state.
Global Store
Provided by @openmrs/esm-framework
(and, specifically, esm-global
); this gives us access to Zustand stores (opens in a new tab). This is useful for storing values that are shared across more than one component and need to be consistent across them. Note that while the underlying implementation uses Zustand, it is preferable to use the framework-provided API (opens in a new tab), e.g.,
// outside of a component
const userStore = createGlobalStore<UserStore>('userStore', { user: null });
// inside a component
const user = useStore<UserStore, User | null>(userStore, state => state.user);
// at some other point
userStore.set((state) => state.user = /* value from somewhere */);
Updating the store using set()
will update all variables subscribed to the store, including (like in the example) user
.
App context
App Context (opens in a new tab) is a mechanism for sharing state across different parts of the application, specifically designed for cross-component communication within the currently active application. Unlike global stores which persist between component renders, App Context is tied to the lifecycle of specific components.
Common use cases for App Context include:
- Sharing state between components that exist in different React trees
- Managing temporary shared state that should only exist while specific components are active
- Coordinating between different parts of a feature (e.g., sharing selected patient data across related components).
The framework provides two hooks for working with App Context:
- useDefineAppContext (opens in a new tab) for defining the context.
- useAppContext (opens in a new tab) for accessing the context.
Defining a context
const [dateRange, setDateRange] = useState<Date[]>([
dayjs().startOf("day").toDate(),
new Date(),
]);
useDefineAppContext<DateFilterContext>("laboratory-date-filter", {
dateRange,
setDateRange,
});
Accessing the context
const { dateRange, setDateRange } = useAppContext<DateFilterContext>(
"laboratory-date-filter"
) ?? {
// Fallback values used when the app context is undefined
dateRange: "fallback-date-range",
setDateRange: "fallback setter function",
};
When to use App Context vs Global Store
- Use App Context when you need to share state between components that should only exist while those components are active in the application.
- Use Global Store when you need state to persist between component renders or across the entire application lifecycle.
Persistent Storage
Persistent storage refers to any storage mechanism that persists beyond a render of the single-page.
The Backend
At least while online, storing persistent data to the backend should be the default. This is generally done through using the REST or FHIR APIs for OpenMRS.
Session Storage
This provides a Storage (opens in a new tab) API for values that persist across a page session. Page sessions generally persist as long as a single browser tab. This should be the preferred storage mechanism for values that need to persist across a page reload boundary.
Local Storage
This provides a Storage (opens in a new tab) API for values that persist until they are changed. They are specific to a web origin, but apply to all tabs and all pages. This is useful for storing user application-level preferences (e.g., language), but should not be used unless the value should be associated with the user-and-browser combination.