📅  最后修改于: 2023-12-03 15:19:44.851000             🧑  作者: Mango
React useState
hook is a built-in hook in React that allows you to manage state within functional components. This hook allows you to store and update the state of a component without having to write a class component.
const [state, setState] = useState(initialState);
useState
takes an initialState
value as an argument and returns two values:
state
: current state of the component.setState
: a function that can update the state of the component.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 value and setCount
is the function that updates the state value.
When the Click me
button is clicked, it invokes the setCount
function which updates the count
value by incrementing it by 1
.
useState
hook only in functional components.useState
conditionally i.e., within if
statements or loops. The state of a component remains the same even if the component re-renders. Therefore, if you use useState
conditionally, the state of the component will not persist on re-render.useState
hook doesn’t merge the old state with the new state like setState
in class components. It completely replaces the old state with the new state. Therefore, if you have multiple states in your component, you will have to use useState
for each state.useState
hook is an important feature in React as it allows you to manage state in a simple and concise way. You can use it to store any value or data within your component and also update it as per your requirement.