The useState
hook in React is used to add state to functional components. It allows you to declare state variables and update them, causing the component to re-render with the updated state. Here's a breakdown of its basic usage:
import React, { useState } from 'react'; function Example() { // Declare a state variable named "count" and its setter function "setCount" const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <!-- Call setCount to update the state when the button is clicked --> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } export default Example;
useState
returns an array with two elements: the current state value and a function to update it.useState
.useState
calls in a single component to manage different state values independently.setCount
), React schedules a re-render of the component with the updated state value.useState
to manage state within them.useState
is easy to understand and use.useState
to avoid stale state issues.