Selected topic
React Hooks
Prefer practical output? Use related tools below while reading.
The useState hook is a built-in Hook in React that allows you to add state to functional components. This means you can now have stateful components without having to write class-based components.
useState() in your functional component, React will add a new state variable and an update function to the component. The state variable is initially set to its default value (which you specify), and the update function allows you to change the state.Here's an example:
jsx
import { useState } from 'react';function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
In this example:
useState hook from React.Counter component, we call useState(0) to initialize a state variable called count with an initial value of 0.useState hook returns an array where the first element is the current count (i.e., the state variable), and the second element is an update function (setCount) that allows us to change the count.setCount function in our button's onClick event handler to increment the count each time it's clicked.useState hook adds a state variable and an update function to a functional component.useState.useState with a simple counter app.