easy-create-react-context
v1.0.1
Published
The tool just encapsulated React.createContext, you can also think of it as my personal black-tech small tool. Hope you enjoy it.
Downloads
9
Maintainers
Readme
easy-create-react-context
The tool just encapsulated React.createContext, but it's
more efficient,
more convenient when compared to Reducer + Context
such a combination and
easier to manage the state of small modules. You can think of it as mini version of MobX, but with the same rendering efficiency.
You can also think of it as my personal black-tech small tool. Hope you enjoy it.
DEMO
Installation
- YARN
yarn add easy-create-react-context
- NPM
npm i easy-create-react-context
Quick Start
- Create context by invoking
getConTexts
, UseProvider
to setcontexts
andvalue
. - Call
updateAsync
ofcontexts
that we declared to run some asynchronous functions.
import { getConTexts, Provider } from 'easy-create-react-context';
type TExample = InstanceType<typeof Example>;
const contexts = getConTexts<TExample>();
class Example {
a = 1;
b(num: number) {
this.a += num;
}
c(num: number) {
contexts.updateAsync((update) => {
setTimeout(() => {
this.a += num;
update();
}, 500);
});
}
}
const Parent = () => {
return (
<Provider<TExample> contexts={contexts} value={new Example()}>
<Child />
</Provider>
);
};
- Invoke
useContext
and usecontexts.getContext
as param.(if you prefer class component, usecontexts.getContext('key').Consumer
instead) - Call
context.dispatch
to update data.
const Child = () => {
const a = useContext(contexts.getContext('a'));
return (
<>
<div>{a}</div>
<button onClick={() => contexts.dispatch({ type: 'b', params: [1] })}>
update
</button>
<button onClick={() => contexts.dispatch("c", 1)}>
async update
</button>
</>
);
};
API
getConTexts
const contexts = getConTexts()
Used to create context, see also following which is related content of contexts
.
Provider
<Provider contexts={contexts} value={value} >...</Provider>
Provider data for children.
- contexts: object (required)
- value: object (required)
context.getContext
const value = React.useContext(context.getContext(key))
Obtain current value of the value
in Provider
.
- key: string (required)
context.dispatch
context.dispatch({type: key, params: argsArray})
// or for short
context.dispatch(key, arg1, arg2, ...argN)
// or used to return something that is return statement of the property of instance
return context.dispatch(key)
Invoke function of value in Provider
and render related components, you can also use it to return what is return statement of the property of instance.
- key: string (required)
- argsArray: Array (optional)
- argN: the NTH param
context.updateAsync
contexts.updateAsync(update=>{ update() })
Used to run asynchronous code.
- update: function (required)
Bug tracker
If you find a bug, please report it here on Github!