r/reactjs • u/chhsiao1981 • Jun 26 '26
Discussion use-thunk: A much simplified global-state-management framework with only modules and (thunk) functions.
https://github.com/chhsiao1981/use-thunk#getting-started
A complete demo site:
https://chhsiao1981.github.io/demo-use-thunk/
https://github.com/chhsiao1981/demo-use-thunk
Global state management (GSM) can be tricky for complicated reactjs applications.
Many GSM frameworks (redux/zustand/etc.) focus on "we have a store, and how do we manage the global states in this store." However, such approach usually leads to create a gigantic function (reducers in redux/RTK, create in zustand).
Similar to many typical programming languages, in use-thunk:
-
File-as-a-Module: Instead of a giant global store, we treat files as independent, isolated domain modules where we implement thunk functions.
-
Object Identification: The module manages state as discrete entity nodes. We use explicit id parameters to identify and operate on individual data objects within that module cleanly.
-
Clean Component Interface: From the component perspective, we simply invoke the module's functions to perform operations.
-
Only One Context Provider: Unlike standard useContext or Redux architectures that require nesting endless providers, we only need exactly one
<ThunkContext></ThunkContext>wrap in ourmain.tsx. It entirely eliminates "Provider Hell" and the architectural uncertainty of managing stacked providers.
A complete example to do increment:
// thunks/increment.ts
import { type Thunk, type State as _State, update } from '@chhsiao1981/use-thunk'
export const name = 'demo/Increment'
export interface State extends _State {
count: number
}
export const defaultState: State = {
count: 0
}
// upsert directly with set.
export const increment = (myID: string, num: number = 1): Thunk<State> => {
return async (set, get) => {
let me = get(myID)
const {count} = me
set(myID, { count: count + num })
}
}
// or we can treat set as dispatching a base action function (update).
export const increment2 = (myID: string): Thunk<State> => {
return async (set, get) => {
let me = get(myID)
const {count} = me
set(update({ count: count + 2 }))
}
}
// or we can use set as dispatching a thunk function.
export const increment3 = (myID: string): Thunk<State> => {
return async (set) => {
set(increment(myID, 3))
}
}
// components/App.tsx
import { useThunk, getState } from '@chhsiao1981/use-thunk'
import * as ModIncrement from './thunks/increment'
export default () => {
const useIncrement = useThunk<ModIncrement.State, typeof ModIncrement>(ModIncrement)
const [increment, doIncrement, incrementID] = getState(useIncrement)
// to render
return (
<div>
<p>count: {increment.count}</p>
<button onClick={() => doIncrement.increment(incrementID)}>increase 1</button>
<button onClick={() => doIncrement.increment2(incrementID)}>increase 2</button>
<button onClick={() => doIncrement.increment3(incrementID)}>increase 3</button>
</div>
)
}
// main.tsx
import { registerThunk, ThunkContext } from "@chhsiao1981/use-thunk";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import * as ModIncrement from './thunks/increment'
import App from "./components/App";
registerThunk(ModIncrement)
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ThunkContext>
<App />
</ThunkContext>
</StrictMode>,
)
Welcome any comments, critiques, or suggestions!
6
u/Honey-Entire Jun 26 '26
What compelling reason is there for this to exist? What does it solve that other libraries don’t or can’t? You didn’t really provide any examples that show why this is any better than existing solutions
1
u/WanderWatterson Jun 26 '26
I think you could use valtio
1
u/Obvious-Monitor8510 Jun 26 '26
interesting approach. the file-as-module pattern is genuinely cleaner than a giant store for domain separation. my concern is the
id-based entity model, which looks like it adds cognitive overhead when your data isn't naturally entity-shaped (settings, UI state, form state, etc.).also curious how this handles derived/computed state across modules, since that's where redux selectors or zustand's computed patterns shine and where simpler thunk models tend to get messy.
the single provider is a real win though. have you benchmarked re-render behavior? with one context wrapping everything, any state update could potentially trigger broad re-renders unless you're using something like
useSyncExternalStoreunder the hood.-3
u/chhsiao1981 Jun 26 '26
Thanks to all the valuable feedbacks~
u/Honey-Entire would like to know the uniqueness of use-thunk, u/WanderWatterson suggested me to check valtio.
Many existing GSM frameworks focus on "store/slice-as-a-singleton", which requires the developers to have their own method to deal with multiple data-objects (ex: [normalized state in Redux](https://redux.js.org/usage/structuring-reducers/normalizing-state-shape)). In addition to coding/naming style differences, I would say the unique part of use-thunk is the id-based entity model. So the Getting Started example can be easily changed to the following 2-counter example:
This example can be easily extended to some complicated scenario, such as an editor supporting tabs dealing with multiple file status.
u/Obvious-Monitor8510 provides several very interesting feedback:
* I am not exactly sure the meaning of "naturally entity-shaped", I would guess that it means the (thunk) module corresponds to a react component. The global state data model can be totally different from the component (ex: the user-info in the demo-use-thunk, as the same user-info is repeatedly used by different components, (Header, Parent, and GrandChild)
* As demonstrated in the original "Getting Started" example, we can treat `id` as a dummy variable if the (thunk) module is a singleton.
* If there are multiple data-objects in a (thunk) module, then `id` is used to identify different data-objects. If the (thunk) module is DB-related, then we can directly use the unique-id of the data-object from the DB. Or as the described example, we can use `genID` to differentiate different data-objects.
2. as "across modules", we can directly use `doA.func(useB, bID)` for cross-module communication. So:
3. "single provider" is actually [the black magic](https://github.com/chhsiao1981/use-thunk/blob/main/src/thunkContext/ThunkContext.tsx#L39), as there are still multiple Context Provider under the hood, but recursively rendering the Context Provider. I believe that the reason why Context Provider cannot be fixed in the `main.tsx` in useContext, is to deal with the multiple-data-object issue (we get the data/state from "nearest appeared Context Provider" when using useContext.) In use-thunk, multiple-data-object issue is resolved through `id`, so we can use this black magic and have all the Context Provider fixed in the `main.tsx` (with the same rendering order.)