Last active
September 24, 2024 21:14
-
-
Save nythrox/79485cc5953613b62604c94793e2fbac to your computer and use it in GitHub Desktop.
extremely simple React helper for sharing state with react context
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, { useRef } from "react"; | |
export const state = <F extends (...args: any[]) => any>(create: F) => { | |
const context = React.createContext<ReturnType<F>>(undefined as any) | |
return { | |
Provider: context.Provider, | |
create, | |
use: () => React.useContext(context), | |
context, | |
} | |
}; |
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
const AppState = state((initialValue: number) => { | |
const [counter, useCounter] = useState(initialValue) | |
return { | |
count, | |
increment: () => setCounter(c => c + 1) | |
} | |
}) | |
const ParentComponent = () => { | |
const state = AppState.create(0) | |
return ( | |
<AppState.Provider value={state} | |
<div> | |
count: { state.count } | |
<ChildComponent/> | |
</div> | |
</AppState.Provier> | |
) | |
} | |
const ChildComponent = () => { | |
const state = AppState.use() | |
return <button onClick={() => state.increment()}/> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment