useState Hook in React

User
usestate in react
Assistant
`useState` is a Hook in React that lets you add **state** to functional components.

### ๐Ÿ”ง Syntax:

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

– `state` is the current state value.
– `setState` is the function to update the state.
– `initialValue` is the starting value of the state.

### ๐Ÿง  Example:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0); // Initial value is 0

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

### ๐Ÿ“Œ Notes:
– Calling `setCount()` updates the state and causes the component to re-render.
– You can store any type in `useState` โ€“ number, string, array, object, etc.

### ๐Ÿ“ฆ Storing an object:

const [user, setUser] = useState({ name: 'Neeraj', age: 30 });

const updateName = () => {
  setUser(prev => ({ ...prev, name: 'Tiwari' }));
};

Let me know if you want to see `useState` with forms, arrays, or async behavior too!

Leave a Comment

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