Click here to Skip to main content
15,886,422 members
Articles / Web Development / React
Tip/Trick

Alternative to React.useState => objectUseState

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
12 Sep 2021CPOL1 min read 3.6K   2  
ObjectuseState - the behavior of React.UseState applies to object properties
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

JavaScript
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sweden Sweden
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --