Stateful Components with useState Hook
React provides the useState hook as a way to manage state in functional components. We can use the useState hook to create stateful components by defining a state variable and an update function.
The useState hook takes an initial state value as an argument and returns an array containing the current state value and a function to update the state value.
Here's an example of how to use the useState hook to create a simple counter component:
1import React, { useState } from 'react';
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 const increment = () => {
7 setCount(count + 1);
8 };
9
10 const decrement = () => {
11 setCount(count - 1);
12 };
13
14 return (
15 <div>
16 <h2>Counter</h2>
17 <p>Count: {count}</p>
18 <button onClick={increment}>Increment</button>
19 <button onClick={decrement}>Decrement</button>
20 </div>
21 );
22}
23
24function App() {
25 return (
26 <div>
27 <h1>Stateful Components with useState Hook</h1>
28 <p>React provides the useState hook as a way to manage state in functional components. We can use the useState hook to create stateful components by defining a state variable and an update function. Let's create a simple Counter component to demonstrate this:</p>
29 <Counter />
30 </div>
31 );
32}
33
34ReactDOM.render(
35 <React.StrictMode>
36 <App />
37 </React.StrictMode>,
38 document.getElementById('root')
39);
In this example, we define a Counter
component that uses the useState hook to create a state variable count
and an update function setCount
. The initial state value is 0
.
The Counter
component renders the current value of count
and two buttons to increment and decrement the count. The increment
and decrement
functions update the count
state using the setCount
function.
We can use the useState hook multiple times in a component to create multiple independent state variables.
The useState hook ensures that the component is re-rendered whenever the state value is updated.
Feel free to experiment with the code and see how the counter component renders and updates the count value on the screen.
xxxxxxxxxx
);
// Replace with stateful component code
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
return (
<div>
<h2>Counter</h2>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
function App() {
return (
<div>
<h1>Stateful Components with useState Hook</h1>