7 - useState Hook in React framework with working code example

useState in React 

The React useState Hook allows you to have state variables in functional components. 

You pass the initial state to this function, and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.


OR

In simple words,

 The Hook takes an initial state value as an argument and returns an updated state value whenever the setter function is called. 


Before using useState we have to import it


import { useState } from 'react';


It can be used like this:

const [state, setState] = useState(initialValue);



Here, the initialValue is the value you want to start with, and state is the current state value that can be used in your component

The setState function can be used to update the state, triggering a re-render of your component.


Example:

Write a working code using useState Hook in React Framework .

In which we can see the how many times we have clicked a button by the count  value written on the button itself 

App.js

import { useState } from 'react';
import './App.css';

export default function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {

    setCount(count + 1);
  }

  return (
    <button onClick={handleClick}>
      You pressed me {count} times
    </button>
  );
}


In this code we can see 

1- We have imported the useState

2- Initial value of count is 0

3- After each click on button (onClick function) setCount increases the value of count by 1.


Image 1 -  useState on Button Working Image


Comments