Skip to content

Instantly share code, notes, and snippets.

@nythrox
Last active September 24, 2024 21:14
Show Gist options
  • Save nythrox/79485cc5953613b62604c94793e2fbac to your computer and use it in GitHub Desktop.
Save nythrox/79485cc5953613b62604c94793e2fbac to your computer and use it in GitHub Desktop.
extremely simple React helper for sharing state with react context
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,
}
};
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