DEV Community

Cover image for useState ()
coding_tarento
coding_tarento

Posted on

useState ()

Hi👋, if you landed up on this page there is good chance that you already know the JavaScript .I believe if you reading this blog that mean you have basic understanding of variables . if your answer is yes then congratulations ! you will understand useState very easily .

lets think about it , what is the purpose of variable?? yep yep yep you are absolutely right ! , the puspose of variable is store some value and we can change the value of variable .finally react talks ...
important note useState hook is only for functional component

useState accepts an initial state and returns two values

  1. The current state.
  2. A function that updates the state.

To use the useState Hook, we first need to import it into our component.

import {useState} from "react"

sample counter using useSate hook:
import {useState} from "react"
import "./styles.css";
export default function App() {
// count is state name and setCount is a setter function
const [count,setCount]=useState(0)
const addHandler =()=>{
setCount(count+1)
}
const substractHandler=()=>{
setCount(count-1)
}
return (
<div>
<div className="heading-name">
Counter App
</div>
<div className="count">
{count}
</div>
<div className="button-container">
<button class="counter-button" onClick={addHandler}> +
</button>
<button class="counter-button" onClick={substractHandler}>
- </button>
</div>
</div>)}

we can able to change the state value by using setter function easily . The count is the current value and setCount is setter function for manipulating count value .
summery :

  1. react hooks are special functions
    1. useState is also a special kind of function which accepts state as an argument it can be anything string, array , object , number
    2. it will return current value and setter function. Hope you love the blog! you can check the sandbox link and play around it.. take carea!!! https://codesandbox.io/s/react-uesstate-hook-counter-mvki7w?file=/src/App.js:0-595

Top comments (0)