To use state in a functional component with React Hooks, you can use the useState
hook that comes with React. Here is an example of how you can use state in a functional component:
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<h1>{count}</h1>
<button onClick={increment}>Increment</button>
</div>
);
};
export default MyComponent;
In the example above, we first import useState
from 'react'. We then call the useState
hook with an initial state value of 0. The useState
hook returns an array with two values - the current state value (count
) and a function to update the state (setCount
).
We can then use count
to display the current count value in our component and use setCount
to update the count value when the "Increment" button is clicked.
By using the useState
hook, we are able to add state to a functional component and update that state without using class components or lifecycle methods.