Advertisement
Guest User

Untitled

a guest
May 26th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. import React, {useMemo, useState, useEffect, useCallback} from 'react';
  2. import {createStore} from 'redux';
  3.  
  4. import { ReduxContext } from './useRedux';
  5.  
  6. export const Redux = ({reducer, enhancer, children}) => {
  7. // Initially create the store for Redux.
  8. const store = useMemo(() => createStore(reducer, undefined, enhancer), [reducer, enhancer]);
  9.  
  10. // Initialize the Redux state.
  11. const [state, setState] = useState(store.getState());
  12.  
  13. // Subscribe to updates from the Redux store.
  14. useEffect(() => {
  15. return store.subscribe(() => {
  16. setState(store.getState());
  17. });
  18. }, [store]);
  19.  
  20. // Cache the dispatch function
  21. const dispatch = useCallback((action) => store.dispatch(action), [store]);
  22.  
  23. // Cache the context data to feed to the `useRedux` hook!
  24. const contextData = useMemo(() => [state, dispatch], [state, dispatch]);
  25.  
  26. return (
  27. <ReduxContext.Provider value={contextData}>
  28. {children}
  29. </ReduxContext.Provider>
  30. );
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement