@oyvindher/react-state-connector
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

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 of useContext(StateContext), and use the render-prop to access the global state!

Package Sidebar

Install

npm i @oyvindher/react-state-connector

Weekly Downloads

0

Version

0.1.0

License

MIT

Unpacked Size

5.79 kB

Total Files

7

Last publish

Collaborators

  • oyvindhermansen