Last active
February 22, 2019 10:05
-
-
Save furugomu/45984c8bb47a8f4d57bbe716e2ebc8f5 to your computer and use it in GitHub Desktop.
useRedux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useMemo, useState, useEffect, useDebugValue } from "react"; | |
import { createStore, Reducer, Action, Dispatch, StoreEnhancer } from "redux"; | |
const useRedux = <S, A extends Action<any>>( | |
reducer: Reducer<S, A>, | |
enhancer?: StoreEnhancer<S, A> | |
): [S, Dispatch<A>] => { | |
// store を一度だけ作る | |
const store = useMemo(() => createStore(reducer, enhancer), [reducer, enhancer]); | |
const [state, setState] = useState(store.getState()); | |
// store の変更を state へ | |
useEffect(() => store.subscribe(() => setState(store.getState())), [store]); | |
useDebugValue(state); | |
return [state, store.dispatch]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment