Skip to content

Instantly share code, notes, and snippets.

@kstulgys
Last active October 14, 2019 10:53
Show Gist options
  • Save kstulgys/f2e372e20f377511b6013e506c618286 to your computer and use it in GitHub Desktop.
Save kstulgys/f2e372e20f377511b6013e506c618286 to your computer and use it in GitHub Desktop.
import React, { useMemo, useContext, createContext } from "react"
import { useImmer } from "use-immer"
const initialState = {
count: 0
}
function makeStore() {
const Context = createContext()
const stateFromStorage = () =>
JSON.parse(localStorage.getItem("state")) || initialState
const Provider = ({ children }) => {
const [state, setState] = useImmer(stateFromStorage)
useMemo(() => localStorage.setItem("state", JSON.stringify(state)), [state])
const contextValue = {
state,
setState
}
return <Context.Provider value={contextValue}>{children}</Context.Provider>
}
const useStore = () => useContext(Context)
return {
Provider,
useStore
}
}
export default makeStore()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment