In React, the useState
hook is used to add state to functional components. It allows you to declare state variables in your functional components. The basic syntax for using useState
is as follows:
jsximport React, { useState } from 'react';
function MyComponent() {
// Declare a state variable named "count" with an initial value of 0
const [count, setCount] = useState(0);
// The "count" variable holds the current state value, and "setCount" is a function to update it
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default MyComponent;
Here's a breakdown of how it works:
Import the useState
hook:
jsximport React, { useState } from 'react';
Declare a state variable:
jsxconst [count, setCount] = useState(0);
count
: The state variable that holds the current state value.setCount
: The function used to update the state. When called, it will re-render the component with the new state value.useState(0)
: The argument passed to useState
is the initial state value. In this example, the initial value of count
is set to 0.Use the state variable in your component:
jsx<p>Count: {count}</p>
You can use the count
variable in your JSX to display the current state.
Update the state with the setter function:
jsx<button onClick={() => setCount(count + 1)}>
Increment
</button>
In this example, clicking the "Increment" button will call setCount
with the updated value of count + 1
, causing a re-render with the new state.
Remember that the argument passed to the setter function (setCount
in this case) can also be a function that takes the previous state as an argument. This is useful when the new state depends on the previous state. Here's an example:
jsx<button onClick={() => setCount(prevCount => prevCount + 1)}>
Increment
</button>
This ensures that the update is based on the latest state value.