Skip to main content

Share Everywhere

Table of contents

Hello react devs in this tutorial i am going to show that how we can use useState() in our functional react component. if we use useState then no need to define your component as class based component. 

It is react hook. So using useState hook we can change our state value easily. If you don't know how react useState hook works then this example is for you to clear your concept.

using useState

Basically usestate took three parameters. Initial state, current state and a method. See the below example

const [count, setValue] = useState(0)

Look here 0 is initial state and we used array destructuring to define current state and method. here count is current state and setValue is method. Now in this example we will create a button and when we will click on this button then the value will be incremented.

Let's see the example.

import React, {useState} from 'react'

function HookCounterThree() {

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

  return (

      <div>

          <form>

               <input

                   type="text"

                   value={name.firstName}

                   onChange={(e) => setName({...name,

                      firstName: e.target.value

                   })}

               />

               <input

                   type="text"

                   value={name.lastName}

                   onChange={(e) => setName({ ...name,

                      lastName: e.target.value

                   })}

               />

               <h2>Your first name is {name.firstName}</h2>

               <h2>Your last name is {name.lastName}</h2>

          </form>

      </div>

  )

}

 

function HookCounter() {

  const [count, setValue] = useState(0)

  return (

      <div>

          <button onClick={() => setValue(count+1)}>Count {count}</button>

      </div>

  )

}


export default HookCounter 
Bạn cảm thấy bài viết này như thế nào?

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
9 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.