Last active
October 14, 2019 10:53
-
-
Save kstulgys/f2e372e20f377511b6013e506c618286 to your computer and use it in GitHub Desktop.
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
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