Học demo nhỏ về React Js useState() Hook ví dụ có tên HookCounter
8th Oct 2022Hello 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
Add new comment