Skip to content

Instantly share code, notes, and snippets.

@furugomu
Last active February 22, 2019 10:05
Show Gist options
  • Save furugomu/45984c8bb47a8f4d57bbe716e2ebc8f5 to your computer and use it in GitHub Desktop.
Save furugomu/45984c8bb47a8f4d57bbe716e2ebc8f5 to your computer and use it in GitHub Desktop.
useRedux
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