What is useState() in React?
What is useState() in React?
useState
is a Hook in React that allows you to add state to functional components. In class components, state is typically managed within the component using this.state
and this.setState
, but Hooks provide a way to work with stateful logic in functional components without converting them to classes.
When you call useState
, you declare a state variable that React will preserve across re-renders. The useState
Hook takes the initial state as its argument, which can be any data type, such as a string, number, object, or array. The initial state is only used during the first render.
Here's the basic syntax of useState
:
const [state, setState] = useState(initialState);
state
is the current state value, and it will be initialized to initialState
on the first render.setState
is a function that allows you to update state
. When you call setState
with a new value, React will re-render the component with the updated state.A key feature of useState
is that it returns an array with exactly two elements. The first element is the current state value, and the second is a function that lets you update it. This is why we use array destructuring to access these two values.
It's important to note that useState
does not merge the new and old state together like this.setState
does in class components. If you're updating an object or an arr...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào