useState Hook in React
August 8, 2025 ยท AI Conversations
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!