I'm trying out the new React Hooks's useEffect
API and it seems to keep running forever, in an infinite loop! I only want the callback in useEffect
to run once. Here's my code for reference:
Click "Run code snippet" to see the "Run useEffect" string is being printed to the console infinitely.
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>
react-hooks
eslint plugin. This would be flagged up by theexhaustive-deps
rule. It would appear the correct solution is to use theuseCallback
hook, more discussion here: github.com/facebook/react/issues/14920#issuecomment-471070149 – Intransigeance