What is a Hook? A Hook is a special function that lets you “hook into” React features. For example,
useState is a Hook that lets you add React state to function components. We’ll learn other Hooks later.When would I use a Hook? If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We’re going to do that right now!
Example of useState Hook function.
import React,{useState} from 'react'
export default function Statehook() {
const [count,setCount] = useState(0);
const [name,setname] = useState('');
const plusbtn = () => {
setCount(count+1);
}
const minusbtn = () => {
setCount(count-1);
}
const inputfun = (e) =>{
const inputval = e.target.value;
setname(inputval);
}
return (
<div>
<h1>This is usestate hook </h1>
<p>{count}</p>
<button onClick={plusbtn}>+ Click</button>
<button onClick={minusbtn}>- Click</button>
<br/><br/>============<br/><br/>
<p>{name}</p>
<input placeholder='enter text here' onChange={inputfun} />
</div>
)
}
0 Comments
Post a Comment