id | title | sidebar_label | sidebar_position | tags | |||||||
---|---|---|---|---|---|---|---|---|---|---|---|
useState hook |
useState Hook Concept |
useState Hook |
1 |
|
Explanation:
useState
is a fundamental hook in React that allows functional components to manage state. State refers to data that changes over time and causes a component to rerender when updated. Prior to hooks, state management was exclusive to class components using this.state
.
When you call useState(initialState)
, it returns an array with two elements:
- The current state (
count
in our example). - A function (
setCount
) that allows you to update the state.
Example:
import React, { useState } from 'react';
function Counter() {
// Declare a state variable named 'count' initialized to 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
{/* On button click, update 'count' using 'setCount' */}
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
You clicked 0 times
{document.getElementById("displayCount").textContent=Number(document.getElementById("displayCount").textContent)+1}}>Click meIn this example, count
is the state variable initialized to 0, and setCount
is the function used to update count
. When the button is clicked, setCount
is called with the new value of count + 1
, causing the component to rerender with the updated count displayed.