11import { useEffect , useReducer } from 'react' ;
22
3+ // useFluxStore essentially combines useReducer and useEffect to use with FluxStores
4+ // useReducer: Used to extract relevant values from the store
5+ // useEffect is used to attach a listener to the store
6+
37export function useFluxStore ( store , storeReducer ) {
4- const [ out , _dispatch ] = useReducer ( ( prevState , store ) => {
5- return storeReducer ( prevState , store )
6- } , storeReducer ( null , store ) )
8+ // Call useReducer and set initial value from current state of store.
9+ const [ out , _dispatch ] = useReducer ( storeReducer , storeReducer ( null , store ) ) ;
710
811 useEffect ( ( ) => {
912 function listener ( ) {
10- _dispatch ( store )
13+ // When store is updated, we dispatch an update to the reducer
14+ _dispatch ( store ) ;
1115 }
1216
13- const token = store . addListener ( listener )
14- return ( ) => {
15- token . remove ( )
16- }
17- } )
18- return out
17+ // Attach reducer's listener to store
18+ const token = store . addListener ( listener ) ;
19+ // On useEffect destruction, remove the listener
20+ return ( ) => token . remove ( ) ;
21+ } ,
22+ [ ] ) ; // We make sure to pass [] so we're not attaching/detaching on every render
23+ return out ; // Reducer value gets returned to useFluxStore
1924}
2025
21- export default useFluxStore
26+ export default useFluxStore ;
0 commit comments