What is useState in React?
useState is a React Hook that allows you to add and manage state in functional components. It returns the current state value and a function to update it. When the state changes, the component automatically re-renders to reflect the new data.
Syntax of useState :
const [stateVariable, setStateFunction] = useState(initialValue);
- stateVariable – The current state value.
- setStateFunction – A function used to update that state.
- initialValue – The starting value of the state.
Example: Basic Counter Using useState
import React, { useState } from "react";
function Counter() {
// Declaring a state variable 'count' with an initial value of 0
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Top comments (0)