Introduction
Welcome to mobx-chunk, a lightweight, type-safe factory for building MobX-powered state slices ("chunks") with minimal boilerplate. Whether you’re managing simple local state or complex asynchronous flows, mobx-chunk helps you stay organized and scalable.
Motivation
- Automatic Actions & Selectors: For every value in your state, mobx-chunk generates a
set${ValueKey}
action and aget${ValueKey}
selector, ensuring consistent naming and reducing manual code. - Async Actions & Loading Flags: Easily define asynchronous processes, with autogenerated loading indicators (
store.isLoading.yourAsyncAction
) so you can track request states in your UI. - Type Safety: Leveraging TypeScript’s type inference, your store, actions, and selectors are fully typed, catching errors at compile time.
- Persistence: Opt into persisting specific fields to local storage or any custom engine, keeping user data across sessions.
- React Integration: Use provided hooks (
useValues
,useComputed
) for seamless, observable-driven updates in your components.
Getting Started
What you’ll need
- React (v17 or above) or React Native
- MobX (v6 or above)
- TypeScript (v4 or above) – optional but recommended for type safety
Install
# with npm
npm install mobx-chunk
# with yarn
yarn add mobx-chunk
Basic Example
Below is a minimal example showing how to define a store chunk and consume it in a React Native component.
1. Create the store chunk
import { createChunk } from "mobx-chunk";
export type TState = {
accessToken: string;
};
export const store = createChunk<TState>({
name: "store",
initialState: {
accessToken: "",
} satisfies TState,
persist: ["accessToken"],
});
export type TStore = typeof store;
This generates:
store.actions.setAccessToken
for updating the tokenstore.selectors.getAccessToken
for reading the tokenstore.asyncActions
for any custom async flows (not included in this example)store.isLoading
flags for each async action (not included in this example)
2. Use in a React component
import React from "react";
import { useValues } from "mobx-chunk";
import { store } from "./your-store-path";
const Component = () => {
const { accessToken } = useValues({
accessToken: () => store.selectors.getAccessToken, // subscribe to accessToken changing
});
return (
/**
* your component goes here
* */
);
};
export default Component;
With mobx-chunk’s hooks, your component will automatically re-render when the selected state changes.
For more details on advanced hooks, persistence configuration, and middleware support, explore the other sections of the documentation.