ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
React.js Tutorial• 5 min read
State with the useState Hook
Tracking and updating dynamic component data over time
The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application.
How useState Works
Import useState from React: import { useState } from "react";.
const [state, setState] = useState(initialValue); destructures the current value and its setter function.
Calling setState(newValue) triggers a component re-render with the updated value.
Interactive Counter with useState
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div style={{ textAlign: 'center', padding: '20px' }}>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)} style={{ padding: '8px 16px', margin: '4px' }}>
Increment +1
</button>
<button onClick={() => setCount(0)} style={{ padding: '8px 16px', margin: '4px' }}>
Reset
</button>
</div>
);
}ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
What does the useState hook return?