Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, {useMemo, useState, useEffect, useCallback} from 'react';
- import {createStore} from 'redux';
- import { ReduxContext } from './useRedux';
- export const Redux = ({reducer, enhancer, children}) => {
- // Initially create the store for Redux.
- const store = useMemo(() => createStore(reducer, undefined, enhancer), [reducer, enhancer]);
- // Initialize the Redux state.
- const [state, setState] = useState(store.getState());
- // Subscribe to updates from the Redux store.
- useEffect(() => {
- return store.subscribe(() => {
- setState(store.getState());
- });
- }, [store]);
- // Cache the dispatch function
- const dispatch = useCallback((action) => store.dispatch(action), [store]);
- // Cache the context data to feed to the `useRedux` hook!
- const contextData = useMemo(() => [state, dispatch], [state, dispatch]);
- return (
- <ReduxContext.Provider value={contextData}>
- {children}
- </ReduxContext.Provider>
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement