The React useState Hook allows us to track state in a function component.
React Frontend Framework
React Tutorial
Advertisement
Google AdSense Slot (LEADERBOARD)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
State Hook
8 min read
•
Chapter 19 of 26
React useState
Initialize state, read state, update state, and manage objects and arrays with the useState Hook.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body style="font-family:sans-serif;padding:20px;">
<div id="root"></div>
<script type="text/babel">
function FavoriteColor() {
const [color, setColor] = React.useState("red");
return (
<div>
<h3>My favorite color is <span style={{color: color}}>{color}</span>!</h3>
<button onClick={() => setColor("blue")} style={{marginRight: "6px"}}>Blue</button>
<button onClick={() => setColor("green")} style={{marginRight: "6px"}}>Green</button>
<button onClick={() => setColor("purple")}>Purple</button>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<FavoriteColor />);
</script>
</body>
</html>
Try it Yourself >>
Opens live sandboxed code editor
Advertisement
Google AdSense Slot (IN-ARTICLE)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
Community Q&A & Discussion
Verified
No questions yet. Be the first to start the discussion!