React bindings for the medama state management library. Provides hooks and components for seamless integration of medama state into React applications.
npm install @medamajs/react
Wrap your app or component tree with ProvideMedama
to make medama state available:
import { ProvideMedama } from '@medamajs/react';
import { createMedama } from 'medama';
import { initialState } from './state';
const pupil = createMedama(initialState);
function App() {
return (
<ProvideMedama pupil={pupil}>
<YourComponents />
</ProvideMedama>
);
}
Subscribe to specific state pieces with automatic re-renders:
import { useMedamaSelector } from '@medamajs/react';
import type { AppState } from './state';
function Counter() {
const count = useMedamaSelector((state: AppState) => state.count);
return <div>{count}</div>;
}
Get access to state reading functionality:
import { useReadMedama } from '@medamajs/react';
import type { AppState } from './state';
function StateReader() {
const readState = useReadMedama<AppState>();
const value = readState((state) => state.someValue);
return <div>{value}</div>;
}
Get access to state update functionality:
import { useUpdateMedama } from '@medamajs/react';
import type { AppState } from './state';
function StateUpdater() {
const setState = useUpdateMedama<AppState>();
return (
<button onClick={() => setState((state) => ({ count: state.count + 1 }))}>
Increment
</button>
);
}
You can nest providers and identify them with IDs:
<ProvideMedama pupil={globalPupil} id="global">
<ProvideMedama pupil={featurePupil} id="feature">
<YourComponents />
</ProvideMedama>
</ProvideMedama>
Access specific provider in hooks:
const globalValue = useMedamaSelector(globalSelector, { id: "global" });
const featureValue = useMedamaSelector(featureSelector, { id: "feature" });
-
ProvideMedama
: Context provider component-
pupil
: Medama pupil instance -
id?
: Optional identifier for nested providers -
children?
: React nodes
-
useMedamaSelector<State, Value>(selector, options?)
useReadMedama<State>(options?)
useUpdateMedama<State>(options?)
All hooks accept optional configuration:
type MedamaReactHookOptions<State> =
| { pupil: Pupil<State>; id?: undefined }
| { id: string | number | symbol; pupil?: undefined }
When options are omitted, hooks use the nearest provider's state.
MIT