useState
?useState
hook is a function that declares a state variable in a functional component.useState
The 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).useState
Let’s create a simple counter that increments by 1 each time you click a button.
useState
import 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.useState
Now, let's create a toggle button that switches between two states: ON and OFF.