📅  最后修改于: 2023-12-03 15:31:23.030000             🧑  作者: Mango
useState()
is a built-in hook in React that allows a functional component to have state variables. It returns an array with two elements: the current state value and a function to update the state value.
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In the above example, count
is the state variable and setCount
is the function to update its value. The initial value of count
is set to 0 using useState(0)
.
setCount(count+1)
, use setCount(prevCount => prevCount+1)
. This ensures that the update is based on the latest state value.useState()
is an essential hook that every React developer should know. By using it, you can easily manage the state of your application and make it more interactive.