Working with a selector and useSubscription
The useStore
hook we created in the previous section returns a whole state object. This means that any small part of the state object change will notify all useStore
hooks and it can cause extra re-renders.
To avoid extra re-renders, we can introduce a selector to return the only part of the state that a component is interested in.
Let's first develop useStoreSelector
.
We use the same createStore
function defined in the previous section and create a store
variable as follows:
const store = createStore({ count1: 0, count2: 0 });
The state in store
has two counts – count1
and count2
.
The useStoreSelector
hook is similar to useStore
, but it receives an additional selector function. It uses the selector function to scope the state:
const useStoreSelector = <T, S>( store: Store<T>, selector: (state: T) => S ) => { const [state, setState] = ...