MENU
Avoiding Unnecessary Firing
We may choose to use the functional update form to avoid firing an effect.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div></div>
<script type="text/babel">
function Counter() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log(999); // not executed repeatedly
const id = setInterval(() => { // setCount(count+1); // count always 0 here. works if [count] is the dependency.
setCount(c => c + 1); // this doesn't depend on the `count` variable outside
}, 1000);
return () => clearInterval(id);
}, []); // this effect doesn't use any variables in the component scope
return <h1>{count}</h1>;
}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<Counter/>);
</script>
</body></html>