This is a component that will make your work a lot easier and also increase the UI update performance when you use too many useState in React.
Background
So for people who use React.useState
, it's really a pain to create multi useState
with [value, setValue]
so I have been thinking what if we could create something like objectUseState
where you can have an object in useState
and simply assign value
and it will trigger the default behavior of setValue
.
Getting Started
npm install @alentoma/usestate
Snack Example
https://snack.expo.dev/@alentoma/usestatealternative
Why Use ObjectUseState
Well imagine that you have too many usestate
. Then you will also have to keep an eye for each and then await and so on.
Well, with this library, you can use an object as a usestate
and it will be able to work the same as a simple react.useState
when you change each property.
This library also makes things faster when you have too many operations and changes to the states as it creates a waiting list behind the code and makes sure each change is applied before the next change to be triggered.
Using the Code
import useState from '@alentoma/usestate'
const state = useState({
counter: 0,
counter2: 0,
text: "",
item: { ItemCounter: 0 },
items:[]
});
React.useEffect(() => {
console.log('counter is Changed');
}, [state.counter]);
React.useEffect(() => {
console.log('ItemCounter is Changed');
}, [state.item.ItemCounter]);
const resetItem=()=> {
state.setValue({
counter: 0,
counter2: 0,
text: "hahaha",
item: { ItemCounter: 0 },
});
}
return (
<>
<Text onPress="{()="> state.counter+=1}>click to append {state.counter} </Text>
<Text onPress="{()="> state.item.ItemCounter+=1}>
click to append {state.item.ItemCounter} </Text>
)
Points of Interest
This library is very useful when you use too many useState
and too many updates to the UI.
As you can build a simple object from all your useState
and also create a waitingList
when you make changes to each of the properties, this will improve performance very much.
History
- 12th September, 2021: Initial version