useState?useState hook is a function that declares a state variable in a functional component.useStateThe basic syntax of useState looks like this:
const [state, setState] = useState(initialValue);
state: The current state value.setState: A function used to update the state.initialValue: The value the state will initially hold (can be any data type like a string, number, array, or object).useStateLet’s create a simple counter that increments by 1 each time you click a button.
useStateimport React, { useState } from "react";
function Counter() {
// Declare a state variable `count` and a function `setCount` to update it.
const [count, setCount] = useState(0);
// Function to increment the count value
const increment = () => setCount(count + 1);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
🔹 Explanation:
useState(0) initializes count with a value of 0.setCount(count + 1) updates the count state each time the button is clicked.useStateNow, let's create a toggle button that switches between two states: ON and OFF.