This happens because useEffect
is triggered after every render, which is the invocation of the Counter()
function in this case of functional components. When you do a setX
call returned from useState
in a useEffect
, React will render that component again, and useEffect
will run again. This causes an infinite loop:
Counter()
→ useEffect()
→ setCount()
→ Counter()
→ useEffect()
→ ... (loop)
To make your useEffect
run only once, pass an empty array []
as the second argument, as seen in the revised snippet below.
The intention of the second argument is to tell React when any of the values in the array argument changes:
useEffect(() => {
setCount(100);
}, [count]); // Only re-run the effect if count changes
You could pass in any number of values into the array and useEffect
will only run when any one of the values change. By passing in an empty array, we're telling React not to track any changes, only run once, effectively simulating componentDidMount
.
function Counter() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('Run useEffect');
setCount(100);
}, []);
return (
<div>
<p>Count: {count}</p>
</div>
);
}
ReactDOM.render(<Counter />, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…