What is useState in react js

useState is a react Hook, its allow to add state to component or we can say add to functional components, its (React) refers to data that over the time can change, Its (useState) is a primary way to manage the data in functional components. useState returns an array with two values

Working process of useState-:

It returns an array with two values
1) First one is state value
2) Second is function to update the state

Example:
How to use useState in functional component:

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable named 'count' and set its initial value to 0
  const [count, setCount] = useState(0);

  return (
    <>
      <h2>You clicked {count} times</h2>
      <button onClick={() => setCount(count + 2)}>
        Click me
      </button>
    </>
  );
}
export default Counter;

Explanation of above example:

Declaration of State-:

const [count, setCount] = useState(0);

count is a declared state variable in above line which is initiaze with 0 value and second is a function “setCount” which we will use for update the state

Rendering the value of State:

{count} inside the <div> will displays the value (current value) of the “count” state.

Updating State:

When you will clicked on the button , it will call the setCount(count + 2) function and updates the count state by incrementing by 2.

Output

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *