3 ms·
For medium-sized state — for example a single-level object — I usually use useReducer, with the "reduce" function a simple destructure merge. The reducer looks
by neolefty 5y ago
For medium-sized state — for example a single-level object — I usually use useReducer, with the "reduce" function a simple destructure merge. The reducer looks like this:
const shallowMergeReducer = <T extends {}>(state: T, action: Partial<T>): T => Object.freeze({
...state,
...action,
})
It ends up looking a lot like the "setExtendedState" function in the article.
Often I'll throw in a few helper functions in a useMemo, too, and then provide the whole thing through Context. It's like a mini-Redux for some section of the app.