React useState in 10 Mins

React useState in 10 Mins

Hello, my all readers, have you ever tried to read about React useState Hooks but didn't understand as much as you wanted? Gone are the days because finally, you have landed at the right place. Until the last night, I was also confused about React useState Hooks but now I am in love with it. So without wasting your precious time, let's start learning React useState Hooks :

State in our Daily Life :

Before starting the concept of React useState Hook, I give you a simple challenge in JavaScript. And the challenge is :

 <h1 id="demo"> I Love Cricket </h1>

 <button onclick="change()">Click Me</button>

Let me know what would be its output.

It's obvious that it will print h1 and button. Everyone knows it. OK great. But could you please do me a favor and if I click on a button it should print I Love Soccer?

Yes, it is too simple. You'll create a function on the button click and change its content from I Love Cricket to I Love Soccer.

function change()
{
 document.getElementById('demo').innerHTML = `I Love Soccer`
}

So if you click on the Button, the content will be changed. Finally, you have completed my simple task. Nothing rocket science here.

But how it is related to React useState Hook ?

Let me explain you with the above example.

  • First, our document was displaying I Love Cricket.

  • When we click on the Button, it was changed to I Love Soccer.

  • Here, we have achieved this functionality easily in our HTML and JavaScript but if you want to do the same task in React, this is not the right way to handle the state.

Actually, If we talk about React, this concept is known as State. Here we have changed our State from I Love Cricket to I Love Soccer.

If I give some more examples of State in React is :

  • When we toggle day/night mode on the website.

  • When we update our shopping cart from one item to 2 or delete all of them.

These are some examples of React JS State. In both the cases that I mentioned above, you need to play with State in React.

In Class Component, this concept is called States.

In Functional Component, this concept is called useState Hook.

useState is a new way of declaring a state in React App.

Start with useState Hooks :

Ok so finally we are going to start our useState Hooks Concept:

Below is our Example.js Component (Functional)

import React, { useState } from 'react'

// Our Component
function Example() {

// Initial Value
    const myArray = useState("Ravi")

// Updated Value 
    function test()
    {
        myArray[1]("Alex")
    }

  return (
   <>
   <h1>{myArray[0]}</h1>
   <button onClick={test}>Click Me</button>
   </>
  )
}

export default Example
  • First, we have imported useState from React Modules.

  • Inside our functional component, we defined the variable myArray.

Actually, useState() gives us 2 values. One is the initial value and the other is the updated value.

So we can say that :

  • myArray[0] = "Ravi"

  • myArray[1] = "Alex" (Our Updated Value, which we'll do it later)

So in the above example, we want an functionality that if we click on Button, the name should be change to Alex from Ravi.

The above example is just for your understanding .

Now we'll see how we can get the same output using Array Destructuring :

useState with Destructuring :

useState() is mostly used with the help of Array Destructuring. I have already written an article on Array Destructuring too. You can read it here : Array Destructuring

This is going to be our same example as we have seen it earlier in this blog.

Below is our Example.js File :

import React, { useState } from 'react'


function Example() {

    const [name, setName]  = useState("Ravi")

    function test()
    {
        setName("Alex")
    }

  return (
   <>
   <h1>{name}</h1>
   <button onClick={test}>Click Me</button>
   </>
  )
}

export default Example

Let's understand it step by step :

  • First, we import React and useState from our modules.

  • Here we are using Functional Component which is Example.js

  • Next, we have used Array Destructuring concept.

  • name will be our Initial value and setName will be our Updated value

    So we can assume that :

    name = Ravi,

    setName = Alex

  • useState("Ravi") > It means by default we have set intial value to Ravi

Again we want a same functionality that if a user click on button, name should be change to Alex from Ravi.

We have also used here onClick function which is {test}. Inside this function, we have written our updated value which is Alex by using setName() Method.

 function test()
    {
        setName("Alex")
    }

I hope you must have basic understanding of useState() Hook. If you still don't understand, then don't worry. You'll must understand by our next example.

Number Increment Example :

Similarly, if we want to increment our number, we can again use useState Hook.

import React, { useState } from 'react'


function Example() {

    const [name, setName]  = useState(0)

    function test()
    {
        setName(name+1)
    }

  return (
   <>
   <h1>{name}</h1>
   <button onClick={test}>Click Me</button>
   </>
  )
}

export default Example

This example is almost similar to our previous one. But here we are just want to updated our number every time when we click on button.

If you click on a button, our number will increase every time.

useState(0)
// If you put here 5 instead of 0, our number will start increasing from number 5.

Now I must say that you have understood about state in Functional Components.

So far we have seen that we can update our Name, Number. But can we use Objects here too ?

The answer is Yes. The useState Hook can be used to keep track of Strings,Numbers,Booleans', Array or Object or combination of any these.

useState Hook with Object :

import React, { useState } from 'react'


function Example() {

// Initial Value     
    const obj = {
        name:"Virat Kohli",
        age:34,
        sport:"Cricket",
        nationality:"Indian"
    }

    const [person, setPerson]  = useState(obj)

// Updated Code
    function test()
    {
       setPerson({
        name:"Lionel Messi",
        age:35,
        sport:"Soccer",
        nationality:"Argentina"
       })
    }



  return (
   <>

   <h1>{person.name}</h1>
   <h2>{person.age}</h2>
   <h3>{person.sport}</h3>
   <h4>{person.nationality}</h4>

   <button onClick={test}>Click Me</button>
   </>
  )
}

export default Example

Dont' worry there is no rocket science here too. Believe me.

  • First, we have created a object obj and displaying the some initial data about Famous Indian Cricketer Virat Kohli.

  • On Button click, our data will change to our updated data which is about Lionel Messi.

    const [person, setPerson]  = useState(obj)
    // Here, obj is our object as we are passing this time Object
    

    useState Hook with Array :

    Similarly, we can also update our Array too with the help of useState.

import React, { useState } from 'react'


function Example() {

 // Initial Data (Fruits List)
   const myArray = [" Apple "," Orange "," Banana "]

    const [person, setPerson]  = useState(myArray)

// Updated Data (Animals List)
    function test()
    {
       setPerson([" Lion "," Tiger "," Fish"])
    }



  return (
   <>

  <h1>{person}</h1>

        <button onClick={test}>Click Me</button>



   </>
  )
}

export default Example

In the above example, we have a list of some fruits stored in an array. On button click, we want to render our updated list which is Animal List.

I guess you now have a fair understanding of useState() Hook in React JS.

If you really love ❤️ this article, please hit a like ✅ or drop a comment. I'll keep posting the articles related to JavaScript and Front End development.