Skip to content

Instantly share code, notes, and snippets.

@pravdomil
Last active November 25, 2019 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pravdomil/d5751dfac71bcd8512daa2b3bdbd7396 to your computer and use it in GitHub Desktop.
Save pravdomil/d5751dfac71bcd8512daa2b3bdbd7396 to your computer and use it in GitHub Desktop.
you might not need redux
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