-
-
Save josefrichter/66e7c6a2e83d07e2e75b0a1cac9f4e95 to your computer and use it in GitHub Desktop.
This file contains 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 * as React from "react"; | |
import { useState, useEffect } from "react"; | |
/** | |
A hook to simply use state between components | |
Usage: | |
// You can put this in an central file and import it too | |
const useStore = createStore({ count: 0 }) | |
// And this is how you use it from any component | |
export function Example() { | |
const [store, setStore] = useStore() | |
const updateCount = () => setStore({ count: store.count + 1 }) | |
return <div onClick={updateCount}>{store.count}</div> | |
} | |
*/ | |
export function createStore<T>(state: T) { | |
let storeState: T = Object.assign({}, state); | |
const storeSetters = new Set(); | |
const setStoreState = (state: Partial<T>) => { | |
storeState = Object.assign({}, storeState, state); | |
storeSetters.forEach(setter => setter(storeState)); | |
}; | |
function useStore(): [T, typeof setStoreState] { | |
const [state, setState] = useState(storeState); | |
useEffect(() => () => storeSetters.delete(setState), []); | |
storeSetters.add(setState); | |
return [state, setStoreState]; | |
} | |
return useStore; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment