DEV Community

Cover image for useState ()

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 =()=>{
const substractHandler=()=>{
return (
<div className="heading-name">
Counter App
<div className="count">
<div className="button-container">
<button class="counter-button" onClick={addHandler}> +
<button class="counter-button" onClick={substractHandler}>
- </button>

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!!!

Top comments (0)