The useState hook is a built-in hook in React that allows functional components to have state. It is used to declare a state variable and provides a way to update that variable. In JavaScript, you can use the useState hook as follows:
import React, { useState } from 'react'; function Example() { // Declare a state variable called "count" and initialize it to 0 const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={() => setCount(count - 1)}>Decrement</button> </div> ); }
In the above example, we import the useState hook from the ‘react’ package. Inside the functional component Example
, we declare a state variable called count
using the useState
hook. The useState
hook returns an array with two elements: the current value of the state variable (count
) and a function to update the state variable (setCount
). We initialize count
to 0.
Inside the return statement, we display the current value of count
using curly braces {count}
. We also have two buttons, one for incrementing the count and another for decrementing it. When the buttons are clicked, we call the setCount
function with the updated value of count
.
This way, whenever the state variable count
is updated using setCount
, React will re-render the component and display the updated value.