May 19, 2024

React Hooks – State Hook Examples

In this tutorial, we would examine more state hook examples. We’ll cover the following sub-topics:

  1. Setting State Based on Previous State Value
  2. useState() with Object
  3. useState() with Array

 

1. Setting State Based on Previous State Values

In this example, we add three button: the first one increments the count, the second one decrements the count and the third one resets the count.

function HookCounter2() {

   const initialCount = 0;
   const [count, setCount] = useState(initialCount)

   return (
     <div>
       <p>{count}</p>
       <button onClick={()=>setCount(count + 1)}>Increment</button>
       <button onClick={()=>setCount(count - 1)}>Decrement</button>
       <button onClick={()=>setCount(initialCount)}>Reset</button>
     </div>
   )
}

There is a problem with this code: this implementation is not safe.

To solve this: instead of passing in the value of the new state variable, we pass in function that have access to the old value.

Therefore the code for the buttons should be adjusted as:

<button onClick={()=>setCount(prevCount => prevCount + 1)}>
    Increment
</button>
<button onClick={()=>setCount(prevCount => prevCount - 1)}>
    Decrement
</button>

So here, prevCount is a function that does the update for use.

 

2. useState() with Objects

In this example, we would have an object: {firstname, lastname”} each initialized to an empty string.

Here we want have two textfields: in the onChange() event of the textfields, we update the values of the firstname and lastname.

I call this component HookCounter3. Completed code is shown below:

function HookCounter3() {

    const [name, setName] = useState({firstName: '', lastName: ''})

    return (
        <div>
            <form>
                
                <input 
                type="text" 
                value={name.firstName} 
                onChange={e=> setName({firstName: e.target.value}) } />

                <input 
                type="text" 
                value={name.lastName} 
                onChange={e=> setName({lastName: e.target.value}) } />

                <h2>The firstname is - {name.firstName}</h2>
                <h2>The lastname is: {name.lastName}</h2>
            </form>
        </div>
    )
}

There’s a problem: the useState() hook does not automatically merge and update an object. So what happens is that: once you change the firstname, the lastname is removed and vice versa.

To fix this problem use the ‘spread operator (…)’.

So you need to change the onChange() events as follows:

onChange={e=> setName({...name, firstName: e.target.value}) } />

The spread operator simply says: spread the name and then set the appropriate property.

Reads, “copy every property in the name object, then only override the firstname property”. Same with lastname.

 

3. useState() with Arrays

Let’s see how the state hook works when the state variable is an array.

In this case, we would first call the useState hook and pass in an empty array.

Then we display the items using and unordered list <ul>. Then we use the map() function to display each list item.

We also add a button to add a random number to the array. On the onClick() event of he button, we call a function that updates the array by appending a random number.

The complete function is shown below:

function HookCounter4() {

    const [items, setItems] = useState([])

    const addItem = () => {
        setItems([...items,{
            id:items.length,
            value: Math.floor(Math.random() * 10) + 1
         }])
    }

    return (
        <div>
            <button onClick={addItem}>Add New/button>
            <ul>
                {
                    items.map(item => (
                    <li key={item.id}>{item.value}/li>)
                    )
                }
            </ul>
        </div>
    )
}

Note how the spread operator(…) is used when the setter function (setItems) is called. And finally, I’ll like to mentioned that the spread operator is a feature of TypeScript. You may want review it.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments