React useEffect runs continuously forever











up vote
2
down vote

favorite












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/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>












share|improve this question


























    up vote
    2
    down vote

    favorite












    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/react@16.7.0-alpha.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

    <div id="app"></div>












    share|improve this question
























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      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/react@16.7.0-alpha.0/umd/react.development.js"></script>
      <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

      <div id="app"></div>












      share|improve this question













      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/react@16.7.0-alpha.0/umd/react.development.js"></script>
      <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

      <div id="app"></div>








      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/react@16.7.0-alpha.0/umd/react.development.js"></script>
      <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

      <div id="app"></div>





      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/react@16.7.0-alpha.0/umd/react.development.js"></script>
      <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

      <div id="app"></div>






      javascript reactjs react-hooks






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 20:40









      Yangshun Tay

      7,76253364




      7,76253364
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          4
          down vote



          accepted










          This happens because useEffect is triggered after every render, which is the invocation of the Counter() function in this case of stateless functional components. When you do a setX call returned from useState in a useEffect, React will render that component again, and useEffect runs 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/react@16.7.0-alpha.0/umd/react.development.js"></script>
          <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

          <div id="app"></div>





          Read up more about useEffect.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243203%2freact-useeffect-runs-continuously-forever%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            4
            down vote



            accepted










            This happens because useEffect is triggered after every render, which is the invocation of the Counter() function in this case of stateless functional components. When you do a setX call returned from useState in a useEffect, React will render that component again, and useEffect runs 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/react@16.7.0-alpha.0/umd/react.development.js"></script>
            <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

            <div id="app"></div>





            Read up more about useEffect.






            share|improve this answer



























              up vote
              4
              down vote



              accepted










              This happens because useEffect is triggered after every render, which is the invocation of the Counter() function in this case of stateless functional components. When you do a setX call returned from useState in a useEffect, React will render that component again, and useEffect runs 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/react@16.7.0-alpha.0/umd/react.development.js"></script>
              <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

              <div id="app"></div>





              Read up more about useEffect.






              share|improve this answer

























                up vote
                4
                down vote



                accepted







                up vote
                4
                down vote



                accepted






                This happens because useEffect is triggered after every render, which is the invocation of the Counter() function in this case of stateless functional components. When you do a setX call returned from useState in a useEffect, React will render that component again, and useEffect runs 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/react@16.7.0-alpha.0/umd/react.development.js"></script>
                <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

                <div id="app"></div>





                Read up more about useEffect.






                share|improve this answer














                This happens because useEffect is triggered after every render, which is the invocation of the Counter() function in this case of stateless functional components. When you do a setX call returned from useState in a useEffect, React will render that component again, and useEffect runs 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/react@16.7.0-alpha.0/umd/react.development.js"></script>
                <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

                <div id="app"></div>





                Read up more about useEffect.






                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/react@16.7.0-alpha.0/umd/react.development.js"></script>
                <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

                <div id="app"></div>





                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/react@16.7.0-alpha.0/umd/react.development.js"></script>
                <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

                <div id="app"></div>






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 10 at 21:08

























                answered Nov 10 at 20:40









                Yangshun Tay

                7,76253364




                7,76253364






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243203%2freact-useeffect-runs-continuously-forever%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Bressuire

                    Vorschmack

                    Quarantine