The useEffect Hook allows you to perform side effects in your components.
React Frontend Framework
React Tutorial
Advertisement
Google AdSense Slot (LEADERBOARD)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
Side Effects
9 min read
•
Chapter 20 of 26
React useEffect
Perform side effects: data fetching, subscriptions, updating DOM, and timers with the useEffect 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 Timer() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const timer = setTimeout(() => setCount(c => c + 1), 1000);
return () => clearTimeout(timer);
}, [count]);
return <h3>I have rendered {count} times!</h3>;
}
ReactDOM.createRoot(document.getElementById("root")).render(<Timer />);
</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!