@oyvindher/react-state-connector
v0.1.0
Published
Simple state management with native React context
Downloads
3
Maintainers
Readme
React state connector
Simple global state management with native React context
Usage
import createState from '@oyvindher/react-state-connector';
interface MyGlobalStateInterface {
counter: number;
}
// Export as a singleton
const { StateProvider, StateContext } = createState<MyGlobalStateInterface>(
counter: 0
)
// Wrap StateProvider around your application.
function App() {
return (
<StateProvider>
{/* Application */}
</StateProvider>
)
}
// Use StateContext together with useContext to access your global state
function Counter() {
const { state, setState } = useContext(StateContext);
return (
<div>
<h1>{state.counter}</h1>
<button onClick={() => setState({...state, counter: +1 })}>Increment</button>
</div>
)
}
Nice to know: You can also use
StateContext.Consumer
instead ofuseContext(StateContext)
, and use the render-prop to access the global state!