Last active
November 25, 2019 11:53
-
-
Save pravdomil/d5751dfac71bcd8512daa2b3bdbd7396 to your computer and use it in GitHub Desktop.
you might not need redux
This file contains hidden or 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
export function createState(reducer) { | |
const State = createContext([]) | |
function getInitialState() { | |
return reducer(undefined, { type:"@@INIT" }) | |
} | |
function StateProvider({ children }) { | |
return createElement(State.Provider, { value: useReducer(reducer, undefined, getInitialState), children }) | |
} | |
function useState(selector, render) { | |
const [state, dispatch] = useContext(State) | |
const partialState = selector(state) | |
return useMemo(() => render(partialState, dispatch), [partialState, dispatch]) | |
} | |
return [StateProvider, useState] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment