Implementing the Context and Subscription pattern
As we learned, using one Context to propagate a global state value has a limitation: it causes extra re-renders.
Module state with Subscription doesn't have such a limitation, but there is another: it only provides a single value for the entire component tree.
We would like to combine Context and Subscription to overcome both limitations. Let's implement this feature. We'll start with createStore
. This is exactly the same implementation we developed in Chapter 4, Sharing Module State with Subscription:
type Store<T> = { getState: () => T; setState: (action: T | ((prev: T) => T)) => void; subscribe: (callback: () => void) => () => void; }; const createStore = <T extends unknown>( initialState: T ): Store<T> => { let state = initialState; const callbacks = new Set<() => void>(); ...