Using State Hooks
In React, the useState hook is used to manage state in functional components. It allows us to add state to our functional components without converting them to class components.
To use the useState hook, we need to import it from the 'react' library:
1import React, { useState } from 'react';
The useState hook accepts an initial state value and returns an array with two elements:
- The current state value
- A function to update the state value
Here's an example of using the useState hook to create a counter component:
1function Counter() {
2 const [count, setCount] = useState(0);
3
4 const incrementCount = () => {
5 setCount(count + 1);
6 };
7
8 return (
9 <div>
10 <p>Count: {count}</p>
11 <button onClick={incrementCount}>Increment</button>
12 </div>
13 );
14}
In this example, we initialize the count state variable with an initial value of 0. The setCount function is used to update the state value when the button is clicked.
By using the useState hook, we can easily manage state in functional components and leverage the benefits of React state management without using class components.
Try implementing a simple counter using the useState hook! See if you can increment the count when the button is clicked.
xxxxxxxxxx
// Using State Hooks
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
}
export default Counter;