react-native-simple-global-state
v0.0.3
Published
react native simple state management
Downloads
3
Readme
Simple Global State for React Native
Installation
npm i react-native-simple-global-state
Basic Usage
Firstly import StateProvider in your App.js
import {StateProvider} from 'react-native-simple-global-state';
Create initial state (obj)
For example increaseNumber
There is the sipmle example for increase number.
const App = () => {
// first create initialState obj.
const initialState = {stateNumber: {number: 0}};
// added reducer simple using state ,and actions
const reducer = (state, action) => {
switch (action.type) {
case 'increaseNumber':
return {
...state,
stateNumber: action.increaseNumber,
};
// other case
default:
return state;
}
};
return (
// added Provider
// given initialState and reducer in stateProvider.
<StateProvider initialState={initialState} reducer={reducer}>
...
</StateProvider>
);
};
How to use in component
First import useStateValue in your components
import {useStateValue} from 'react-native-simple-global-state';
usage in component
const MyButton = () => {
const [{stateNumber}, dispatch] = useStateValue();
//statenumber is your number, dispach for action.
const onPress = () => {
dispatch({
// type=> action.type
type: 'increaseNumber',
// action
increaseNumber: {number: stateNumber.number + 1},
});
};
return (
<TouchableOpacity onPress={onPress} >
<Text>Press Me!</Text>
</TouchableOpacity>
);
};
export default MyButton;
import {useStateValue} from from 'react-native-simple-global-state';
const MyText = () => {
const [{stateNumber}] = useStateValue();
return (
<View>
<Text>{stateNumber.number}</Text>
</View>
);
};
export default MyText;