Quick Start
Check the key points of the Getting Started page with a working example all at once.
1. Install
@byeolnaerim/global-rx-stateuses React hooks and RxJS BehaviorSubjectSo the app needs to have react, rxjstogether.
bash
npm install @byeolnaerim/global-rx-state rxjs react3. Use createRxStateTuple if a runtime key is needed
when the name is determined at runtime, such as workspace id received from the server, route parameters, or the name of the tab clicked by the user, createRxStateTuplethis is natural. The example below uses different draft stores for each tab.
tsx
import { createRxStateTuple } from "@byeolnaerim/global-rx-state";
function RuntimeTabDraftSample() {
const [setActiveTab, , useActiveTab] = createRxStateTuple(
"profile",
"docsQuickActiveTab",
{ storage: "sessionstorage" },
);
const activeTab = useActiveTab();
const [setDraft, , useDraft] = createRxStateTuple(
{ content: "" },
`docsQuickDraft:${activeTab}`,
{ storage: "sessionstorage" },
);
const draft = useDraft();
return (
<Paper variant="outlined" sx={{ p: 2, borderRadius: 3 }}>
<Stack spacing={1.5}>
<Stack direction="row" spacing={1}>
{["profile", "settings", "billing"].map((tabName) => (
<Button
key={tabName}
variant={
activeTab === tabName ? "contained" : "outlined"
}
onClick={() => setActiveTab(tabName)}
>
{tabName}
</Button>
))}
</Stack>
<TextField
label={`${activeTab} draft`}
value={draft.content}
onChange={(event) =>
setDraft({ content: event.target.value })
}
fullWidth
/>
</Stack>
</Paper>
);
}4. Gather change rules in the reducer
Simple values are sufficient with a setter, but if the state changes based on multiple actions or values depend on each other, createRxReducerit's safer to gather change rules in one place.
tsx
type TodoAction =
| { type: "add"; text: string }
| { type: "reset" };
function todoReducer(state: TodoState, action: TodoAction): TodoState {
switch (action.type) {
case "add":
return { items: [...state.items, action.text] };
case "reset":
return { items: [] };
default:
return state;
}
}
const { dispatchTodo, useTodo } = createRxReducer(
{ items: [] },
todoReducer,
"todo",
);