78

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>

2 Answers 2

134

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>

Read up more about useEffect.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the solution, however if you are using the react-hooks eslint plugin. This would be flagged up by the exhaustive-deps rule. It would appear the correct solution is to use the useCallback hook, more discussion here: github.com/facebook/react/issues/14920#issuecomment-471070149
5

You are running into a infinite loop because there is no dependency provided to the written useEffect.

To avoid an infinite loop when using the useEffect hook, make sure to provide a dependency array that includes all the variables that the effect depends on

For example, if you only want the effect to run once when the component mounts, you can pass an empty dependency array like this:

useEffect(() => {
   // effect code here
}, [])

If you want the effect to run whenever a specific variable changes, you can include that variable in the dependency array:

const [count, setCount] = useState(0);

useEffect(() => {
  // effect code here
}, [count])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.