A simple react hook based provider that can be used for storing simple state for you application.
Following from the amazing pattern by Kent C. Dodds, this package allows you to quickly create new providers with state and set state functions.
First install the package in your project:
npm install simple-stateful-provider
Import the create createProvider
function where you want to use the provider:
import createProvider from 'simple-stateful-provider';
Create a new provider using array destructuring, choosing the names for the provider, state hook and set state hook.
const [
DemoProvider,
useDemoState,
] = createProvider();
createProvider
also takes an optional initial state value and name.
Then use the Provider as you would any React provider
//app.js
return (
<DemoProvider>
<App/>
</DemoProvider>
)
To read the state from the provider you can use the useDemoState
hook.
const ExampleView = () => {
const { state } = useDemoState();
return (
<p>
STATE: {JSON.stringify(state)}
</p>
)
}
To set the state from the provider you can use the useDemoSetState
hook.
const ExampleSet = () => {
const { state, setState } = useDemoState();
return (
<p>
<input
value={state || ''}
onChange={evt => {
setState(evt.target.value)
}}
/>
</p>
)
}
To see fully working demos check the demo code.