React hooks: What/Why `useEffect`?











up vote
4
down vote

favorite
5












Concerning the newly proposed React Effect Hook;




  1. What are the advantages and use cases of the Effect hook (useEffect())?


  2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?



The documentation states that:




Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase).




but I think it was already common knowledge to have these behaviors in lifecycle methods like componentDidUpdate, etc. instead of the render method.



There's also the mention that:




The function passed to useEffect will run after the render is committed to the screen.




but isn't that what componentDidMount & componentDidUpdate do anyways?










share|improve this question




















  • 3




    Can you compare your question to the parts in the documentation that you don't understand?
    – Mark C.
    Oct 29 at 18:23










  • @MarkC. Added more info to make question less broad.
    – Mirodinho
    Oct 29 at 19:18










  • You could ask in the official repo your questions if the current documentation is not clear. The official doc asked also to raise any questions readers have to the github as a feedback. This doesn't fit here very well. All answers you may get a here of a digest of all available blog posts. You already got such an answer. But if you do ask in the official repo, and if they think the documentation needs an update, it will happen. By doing that many people will be helpful.
    – Arup Rakshit
    Oct 29 at 19:28

















up vote
4
down vote

favorite
5












Concerning the newly proposed React Effect Hook;




  1. What are the advantages and use cases of the Effect hook (useEffect())?


  2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?



The documentation states that:




Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase).




but I think it was already common knowledge to have these behaviors in lifecycle methods like componentDidUpdate, etc. instead of the render method.



There's also the mention that:




The function passed to useEffect will run after the render is committed to the screen.




but isn't that what componentDidMount & componentDidUpdate do anyways?










share|improve this question




















  • 3




    Can you compare your question to the parts in the documentation that you don't understand?
    – Mark C.
    Oct 29 at 18:23










  • @MarkC. Added more info to make question less broad.
    – Mirodinho
    Oct 29 at 19:18










  • You could ask in the official repo your questions if the current documentation is not clear. The official doc asked also to raise any questions readers have to the github as a feedback. This doesn't fit here very well. All answers you may get a here of a digest of all available blog posts. You already got such an answer. But if you do ask in the official repo, and if they think the documentation needs an update, it will happen. By doing that many people will be helpful.
    – Arup Rakshit
    Oct 29 at 19:28















up vote
4
down vote

favorite
5









up vote
4
down vote

favorite
5






5





Concerning the newly proposed React Effect Hook;




  1. What are the advantages and use cases of the Effect hook (useEffect())?


  2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?



The documentation states that:




Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase).




but I think it was already common knowledge to have these behaviors in lifecycle methods like componentDidUpdate, etc. instead of the render method.



There's also the mention that:




The function passed to useEffect will run after the render is committed to the screen.




but isn't that what componentDidMount & componentDidUpdate do anyways?










share|improve this question















Concerning the newly proposed React Effect Hook;




  1. What are the advantages and use cases of the Effect hook (useEffect())?


  2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?



The documentation states that:




Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase).




but I think it was already common knowledge to have these behaviors in lifecycle methods like componentDidUpdate, etc. instead of the render method.



There's also the mention that:




The function passed to useEffect will run after the render is committed to the screen.




but isn't that what componentDidMount & componentDidUpdate do anyways?







javascript reactjs react-hooks






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 30 at 8:09









skyboyer

3,18611128




3,18611128










asked Oct 29 at 18:12









Mirodinho

497718




497718








  • 3




    Can you compare your question to the parts in the documentation that you don't understand?
    – Mark C.
    Oct 29 at 18:23










  • @MarkC. Added more info to make question less broad.
    – Mirodinho
    Oct 29 at 19:18










  • You could ask in the official repo your questions if the current documentation is not clear. The official doc asked also to raise any questions readers have to the github as a feedback. This doesn't fit here very well. All answers you may get a here of a digest of all available blog posts. You already got such an answer. But if you do ask in the official repo, and if they think the documentation needs an update, it will happen. By doing that many people will be helpful.
    – Arup Rakshit
    Oct 29 at 19:28
















  • 3




    Can you compare your question to the parts in the documentation that you don't understand?
    – Mark C.
    Oct 29 at 18:23










  • @MarkC. Added more info to make question less broad.
    – Mirodinho
    Oct 29 at 19:18










  • You could ask in the official repo your questions if the current documentation is not clear. The official doc asked also to raise any questions readers have to the github as a feedback. This doesn't fit here very well. All answers you may get a here of a digest of all available blog posts. You already got such an answer. But if you do ask in the official repo, and if they think the documentation needs an update, it will happen. By doing that many people will be helpful.
    – Arup Rakshit
    Oct 29 at 19:28










3




3




Can you compare your question to the parts in the documentation that you don't understand?
– Mark C.
Oct 29 at 18:23




Can you compare your question to the parts in the documentation that you don't understand?
– Mark C.
Oct 29 at 18:23












@MarkC. Added more info to make question less broad.
– Mirodinho
Oct 29 at 19:18




@MarkC. Added more info to make question less broad.
– Mirodinho
Oct 29 at 19:18












You could ask in the official repo your questions if the current documentation is not clear. The official doc asked also to raise any questions readers have to the github as a feedback. This doesn't fit here very well. All answers you may get a here of a digest of all available blog posts. You already got such an answer. But if you do ask in the official repo, and if they think the documentation needs an update, it will happen. By doing that many people will be helpful.
– Arup Rakshit
Oct 29 at 19:28






You could ask in the official repo your questions if the current documentation is not clear. The official doc asked also to raise any questions readers have to the github as a feedback. This doesn't fit here very well. All answers you may get a here of a digest of all available blog posts. You already got such an answer. But if you do ask in the official repo, and if they think the documentation needs an update, it will happen. By doing that many people will be helpful.
– Arup Rakshit
Oct 29 at 19:28














2 Answers
2






active

oldest

votes

















up vote
2
down vote



accepted













  1. What are the advantages and use cases of the Effect hook (useEffect())?




    Advantages



    Primarily, hooks in general enable the extraction and reuse of stateful logic that is common across multiple components without the burden of higher order components or render props.



    A secondary benefit (of Effect hooks in particular) is the avoidance of bugs that might otherwise arise if state-dependent side effects are not properly handled within componentDidUpdate (since Effect hooks ensure that such side effects are setup and torn-down on every render).



    See also the peformance and readability benefits detailed below.



     



    Use cases



    Any component that implements stateful logic using lifecycle methods—the Effect hook is a "Better Way".



     





  2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?




    Why it's preferable



    Because of the advantages detailed above and below.



     



    How it differs from lifecycle methods



    Performance



    Effect hooks—




    • feel more responsive than lifecycle methods because they don't block the browser from updating the screen;

    • will however setup and tear-down side effects on every render, which could be expensive…

    • …so can be optimised to be skipped entirely unless specific state has been updated.


     



    Readability



    Effect hooks result in:





    • simpler and more maintainable components, owing to an ability to split unrelated behaviour that previously had to be expressed across the same set of lifecycle methods into a single hook for each such behaviour—for example:



      componentDidMount() {
      prepareBehaviourOne();
      prepareBehaviourTwo();
      }

      componentDidUnmount() {
      releaseBehaviourOne();
      releaseBehaviourTwo();
      }


      becomes:



      useEffect(() => {
      prepareBehaviourOne();
      return releaseBehaviourOne;
      });

      useEffect(() => {
      prepareBehaviourTwo();
      return releaseBehaviourTwo;
      });


      Notice that code relating to BehaviourOne is now distinctly separated from that relating to BehaviourTwo, whereas before it was intermingled within each lifecycle method.




    • less boilerplate, owing to an elimination of any need to repeat the same code across multiple lifecycle methods (such as is common between componentDidMount and componentDidUpdate)—for example:



      componentDidMount() {
      doStuff();
      }

      componentDidUpdate() {
      doStuff();
      }


      becomes:



      useEffect(doStuff); // you'll probably use an arrow function in reality









share|improve this answer




























    up vote
    5
    down vote













    Here is an example from ReactConf2018 Dan Abramov's talk explaining the difference:





    Here are the few findings from the below example:




    1. You'll writing less boilerplate code using hooks

    2. Accessing lifecycles updates and states updates with useEffect()

    3. Regarding performace one aspect is:



    Unlike componentDidMount and componentDidUpdate, the function passed to useEffect fires after layout and paint, during a deferred event





    1. Code sharing will too much easy and useEffect() can be implemented multiple times for different purposes within the same component.

    2. you can control component re render more efficiently by passing an array as second argument to useEffect() hook that is very effective when you just pass empty array to render component on only mounting and unmounting.

    3. Use Multiple useEffect() hooks to Separate Concerns and react will:



    Hooks lets us split the code based on what it is doing rather than a lifecycle method name. React will apply every effect used by the component, in the order they were specified






    Using Classes:



    class Example extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
    count: 0
    };
    }

    componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
    }

    componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
    }

    render() {
    return (
    <div>
    <p>You clicked {this.state.count} times</p>
    <button onClick={() => this.setState({ count: this.state.count + 1 })}>
    Click me
    </button>
    </div>
    );
    }
    }


    Using Hooks:



    import { useState, useEffect } from 'react';

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

    // Similar to componentDidMount and componentDidUpdate:
    useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
    });

    return (
    <div>
    <p>You clicked {count} times</p>
    <button onClick={() => setCount(count + 1)}>
    Click me
    </button>
    </div>
    );
    }





    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',
      autoActivateHeartbeat: false,
      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%2f53051465%2freact-hooks-what-why-useeffect%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      2
      down vote



      accepted













      1. What are the advantages and use cases of the Effect hook (useEffect())?




        Advantages



        Primarily, hooks in general enable the extraction and reuse of stateful logic that is common across multiple components without the burden of higher order components or render props.



        A secondary benefit (of Effect hooks in particular) is the avoidance of bugs that might otherwise arise if state-dependent side effects are not properly handled within componentDidUpdate (since Effect hooks ensure that such side effects are setup and torn-down on every render).



        See also the peformance and readability benefits detailed below.



         



        Use cases



        Any component that implements stateful logic using lifecycle methods—the Effect hook is a "Better Way".



         





      2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?




        Why it's preferable



        Because of the advantages detailed above and below.



         



        How it differs from lifecycle methods



        Performance



        Effect hooks—




        • feel more responsive than lifecycle methods because they don't block the browser from updating the screen;

        • will however setup and tear-down side effects on every render, which could be expensive…

        • …so can be optimised to be skipped entirely unless specific state has been updated.


         



        Readability



        Effect hooks result in:





        • simpler and more maintainable components, owing to an ability to split unrelated behaviour that previously had to be expressed across the same set of lifecycle methods into a single hook for each such behaviour—for example:



          componentDidMount() {
          prepareBehaviourOne();
          prepareBehaviourTwo();
          }

          componentDidUnmount() {
          releaseBehaviourOne();
          releaseBehaviourTwo();
          }


          becomes:



          useEffect(() => {
          prepareBehaviourOne();
          return releaseBehaviourOne;
          });

          useEffect(() => {
          prepareBehaviourTwo();
          return releaseBehaviourTwo;
          });


          Notice that code relating to BehaviourOne is now distinctly separated from that relating to BehaviourTwo, whereas before it was intermingled within each lifecycle method.




        • less boilerplate, owing to an elimination of any need to repeat the same code across multiple lifecycle methods (such as is common between componentDidMount and componentDidUpdate)—for example:



          componentDidMount() {
          doStuff();
          }

          componentDidUpdate() {
          doStuff();
          }


          becomes:



          useEffect(doStuff); // you'll probably use an arrow function in reality









      share|improve this answer

























        up vote
        2
        down vote



        accepted













        1. What are the advantages and use cases of the Effect hook (useEffect())?




          Advantages



          Primarily, hooks in general enable the extraction and reuse of stateful logic that is common across multiple components without the burden of higher order components or render props.



          A secondary benefit (of Effect hooks in particular) is the avoidance of bugs that might otherwise arise if state-dependent side effects are not properly handled within componentDidUpdate (since Effect hooks ensure that such side effects are setup and torn-down on every render).



          See also the peformance and readability benefits detailed below.



           



          Use cases



          Any component that implements stateful logic using lifecycle methods—the Effect hook is a "Better Way".



           





        2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?




          Why it's preferable



          Because of the advantages detailed above and below.



           



          How it differs from lifecycle methods



          Performance



          Effect hooks—




          • feel more responsive than lifecycle methods because they don't block the browser from updating the screen;

          • will however setup and tear-down side effects on every render, which could be expensive…

          • …so can be optimised to be skipped entirely unless specific state has been updated.


           



          Readability



          Effect hooks result in:





          • simpler and more maintainable components, owing to an ability to split unrelated behaviour that previously had to be expressed across the same set of lifecycle methods into a single hook for each such behaviour—for example:



            componentDidMount() {
            prepareBehaviourOne();
            prepareBehaviourTwo();
            }

            componentDidUnmount() {
            releaseBehaviourOne();
            releaseBehaviourTwo();
            }


            becomes:



            useEffect(() => {
            prepareBehaviourOne();
            return releaseBehaviourOne;
            });

            useEffect(() => {
            prepareBehaviourTwo();
            return releaseBehaviourTwo;
            });


            Notice that code relating to BehaviourOne is now distinctly separated from that relating to BehaviourTwo, whereas before it was intermingled within each lifecycle method.




          • less boilerplate, owing to an elimination of any need to repeat the same code across multiple lifecycle methods (such as is common between componentDidMount and componentDidUpdate)—for example:



            componentDidMount() {
            doStuff();
            }

            componentDidUpdate() {
            doStuff();
            }


            becomes:



            useEffect(doStuff); // you'll probably use an arrow function in reality









        share|improve this answer























          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted









          1. What are the advantages and use cases of the Effect hook (useEffect())?




            Advantages



            Primarily, hooks in general enable the extraction and reuse of stateful logic that is common across multiple components without the burden of higher order components or render props.



            A secondary benefit (of Effect hooks in particular) is the avoidance of bugs that might otherwise arise if state-dependent side effects are not properly handled within componentDidUpdate (since Effect hooks ensure that such side effects are setup and torn-down on every render).



            See also the peformance and readability benefits detailed below.



             



            Use cases



            Any component that implements stateful logic using lifecycle methods—the Effect hook is a "Better Way".



             





          2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?




            Why it's preferable



            Because of the advantages detailed above and below.



             



            How it differs from lifecycle methods



            Performance



            Effect hooks—




            • feel more responsive than lifecycle methods because they don't block the browser from updating the screen;

            • will however setup and tear-down side effects on every render, which could be expensive…

            • …so can be optimised to be skipped entirely unless specific state has been updated.


             



            Readability



            Effect hooks result in:





            • simpler and more maintainable components, owing to an ability to split unrelated behaviour that previously had to be expressed across the same set of lifecycle methods into a single hook for each such behaviour—for example:



              componentDidMount() {
              prepareBehaviourOne();
              prepareBehaviourTwo();
              }

              componentDidUnmount() {
              releaseBehaviourOne();
              releaseBehaviourTwo();
              }


              becomes:



              useEffect(() => {
              prepareBehaviourOne();
              return releaseBehaviourOne;
              });

              useEffect(() => {
              prepareBehaviourTwo();
              return releaseBehaviourTwo;
              });


              Notice that code relating to BehaviourOne is now distinctly separated from that relating to BehaviourTwo, whereas before it was intermingled within each lifecycle method.




            • less boilerplate, owing to an elimination of any need to repeat the same code across multiple lifecycle methods (such as is common between componentDidMount and componentDidUpdate)—for example:



              componentDidMount() {
              doStuff();
              }

              componentDidUpdate() {
              doStuff();
              }


              becomes:



              useEffect(doStuff); // you'll probably use an arrow function in reality









          share|improve this answer















          1. What are the advantages and use cases of the Effect hook (useEffect())?




            Advantages



            Primarily, hooks in general enable the extraction and reuse of stateful logic that is common across multiple components without the burden of higher order components or render props.



            A secondary benefit (of Effect hooks in particular) is the avoidance of bugs that might otherwise arise if state-dependent side effects are not properly handled within componentDidUpdate (since Effect hooks ensure that such side effects are setup and torn-down on every render).



            See also the peformance and readability benefits detailed below.



             



            Use cases



            Any component that implements stateful logic using lifecycle methods—the Effect hook is a "Better Way".



             





          2. Why would it be preferable & how does it differ over componentDidMount/componentDidUpdate/componentWillUnmount (performance/readability)?




            Why it's preferable



            Because of the advantages detailed above and below.



             



            How it differs from lifecycle methods



            Performance



            Effect hooks—




            • feel more responsive than lifecycle methods because they don't block the browser from updating the screen;

            • will however setup and tear-down side effects on every render, which could be expensive…

            • …so can be optimised to be skipped entirely unless specific state has been updated.


             



            Readability



            Effect hooks result in:





            • simpler and more maintainable components, owing to an ability to split unrelated behaviour that previously had to be expressed across the same set of lifecycle methods into a single hook for each such behaviour—for example:



              componentDidMount() {
              prepareBehaviourOne();
              prepareBehaviourTwo();
              }

              componentDidUnmount() {
              releaseBehaviourOne();
              releaseBehaviourTwo();
              }


              becomes:



              useEffect(() => {
              prepareBehaviourOne();
              return releaseBehaviourOne;
              });

              useEffect(() => {
              prepareBehaviourTwo();
              return releaseBehaviourTwo;
              });


              Notice that code relating to BehaviourOne is now distinctly separated from that relating to BehaviourTwo, whereas before it was intermingled within each lifecycle method.




            • less boilerplate, owing to an elimination of any need to repeat the same code across multiple lifecycle methods (such as is common between componentDidMount and componentDidUpdate)—for example:



              componentDidMount() {
              doStuff();
              }

              componentDidUpdate() {
              doStuff();
              }


              becomes:



              useEffect(doStuff); // you'll probably use an arrow function in reality










          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Oct 29 at 19:48









          eggyal

          97.3k18145191




          97.3k18145191
























              up vote
              5
              down vote













              Here is an example from ReactConf2018 Dan Abramov's talk explaining the difference:





              Here are the few findings from the below example:




              1. You'll writing less boilerplate code using hooks

              2. Accessing lifecycles updates and states updates with useEffect()

              3. Regarding performace one aspect is:



              Unlike componentDidMount and componentDidUpdate, the function passed to useEffect fires after layout and paint, during a deferred event





              1. Code sharing will too much easy and useEffect() can be implemented multiple times for different purposes within the same component.

              2. you can control component re render more efficiently by passing an array as second argument to useEffect() hook that is very effective when you just pass empty array to render component on only mounting and unmounting.

              3. Use Multiple useEffect() hooks to Separate Concerns and react will:



              Hooks lets us split the code based on what it is doing rather than a lifecycle method name. React will apply every effect used by the component, in the order they were specified






              Using Classes:



              class Example extends React.Component {
              constructor(props) {
              super(props);
              this.state = {
              count: 0
              };
              }

              componentDidMount() {
              document.title = `You clicked ${this.state.count} times`;
              }

              componentDidUpdate() {
              document.title = `You clicked ${this.state.count} times`;
              }

              render() {
              return (
              <div>
              <p>You clicked {this.state.count} times</p>
              <button onClick={() => this.setState({ count: this.state.count + 1 })}>
              Click me
              </button>
              </div>
              );
              }
              }


              Using Hooks:



              import { useState, useEffect } from 'react';

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

              // Similar to componentDidMount and componentDidUpdate:
              useEffect(() => {
              // Update the document title using the browser API
              document.title = `You clicked ${count} times`;
              });

              return (
              <div>
              <p>You clicked {count} times</p>
              <button onClick={() => setCount(count + 1)}>
              Click me
              </button>
              </div>
              );
              }





              share|improve this answer



























                up vote
                5
                down vote













                Here is an example from ReactConf2018 Dan Abramov's talk explaining the difference:





                Here are the few findings from the below example:




                1. You'll writing less boilerplate code using hooks

                2. Accessing lifecycles updates and states updates with useEffect()

                3. Regarding performace one aspect is:



                Unlike componentDidMount and componentDidUpdate, the function passed to useEffect fires after layout and paint, during a deferred event





                1. Code sharing will too much easy and useEffect() can be implemented multiple times for different purposes within the same component.

                2. you can control component re render more efficiently by passing an array as second argument to useEffect() hook that is very effective when you just pass empty array to render component on only mounting and unmounting.

                3. Use Multiple useEffect() hooks to Separate Concerns and react will:



                Hooks lets us split the code based on what it is doing rather than a lifecycle method name. React will apply every effect used by the component, in the order they were specified






                Using Classes:



                class Example extends React.Component {
                constructor(props) {
                super(props);
                this.state = {
                count: 0
                };
                }

                componentDidMount() {
                document.title = `You clicked ${this.state.count} times`;
                }

                componentDidUpdate() {
                document.title = `You clicked ${this.state.count} times`;
                }

                render() {
                return (
                <div>
                <p>You clicked {this.state.count} times</p>
                <button onClick={() => this.setState({ count: this.state.count + 1 })}>
                Click me
                </button>
                </div>
                );
                }
                }


                Using Hooks:



                import { useState, useEffect } from 'react';

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

                // Similar to componentDidMount and componentDidUpdate:
                useEffect(() => {
                // Update the document title using the browser API
                document.title = `You clicked ${count} times`;
                });

                return (
                <div>
                <p>You clicked {count} times</p>
                <button onClick={() => setCount(count + 1)}>
                Click me
                </button>
                </div>
                );
                }





                share|improve this answer

























                  up vote
                  5
                  down vote










                  up vote
                  5
                  down vote









                  Here is an example from ReactConf2018 Dan Abramov's talk explaining the difference:





                  Here are the few findings from the below example:




                  1. You'll writing less boilerplate code using hooks

                  2. Accessing lifecycles updates and states updates with useEffect()

                  3. Regarding performace one aspect is:



                  Unlike componentDidMount and componentDidUpdate, the function passed to useEffect fires after layout and paint, during a deferred event





                  1. Code sharing will too much easy and useEffect() can be implemented multiple times for different purposes within the same component.

                  2. you can control component re render more efficiently by passing an array as second argument to useEffect() hook that is very effective when you just pass empty array to render component on only mounting and unmounting.

                  3. Use Multiple useEffect() hooks to Separate Concerns and react will:



                  Hooks lets us split the code based on what it is doing rather than a lifecycle method name. React will apply every effect used by the component, in the order they were specified






                  Using Classes:



                  class Example extends React.Component {
                  constructor(props) {
                  super(props);
                  this.state = {
                  count: 0
                  };
                  }

                  componentDidMount() {
                  document.title = `You clicked ${this.state.count} times`;
                  }

                  componentDidUpdate() {
                  document.title = `You clicked ${this.state.count} times`;
                  }

                  render() {
                  return (
                  <div>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.setState({ count: this.state.count + 1 })}>
                  Click me
                  </button>
                  </div>
                  );
                  }
                  }


                  Using Hooks:



                  import { useState, useEffect } from 'react';

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

                  // Similar to componentDidMount and componentDidUpdate:
                  useEffect(() => {
                  // Update the document title using the browser API
                  document.title = `You clicked ${count} times`;
                  });

                  return (
                  <div>
                  <p>You clicked {count} times</p>
                  <button onClick={() => setCount(count + 1)}>
                  Click me
                  </button>
                  </div>
                  );
                  }





                  share|improve this answer














                  Here is an example from ReactConf2018 Dan Abramov's talk explaining the difference:





                  Here are the few findings from the below example:




                  1. You'll writing less boilerplate code using hooks

                  2. Accessing lifecycles updates and states updates with useEffect()

                  3. Regarding performace one aspect is:



                  Unlike componentDidMount and componentDidUpdate, the function passed to useEffect fires after layout and paint, during a deferred event





                  1. Code sharing will too much easy and useEffect() can be implemented multiple times for different purposes within the same component.

                  2. you can control component re render more efficiently by passing an array as second argument to useEffect() hook that is very effective when you just pass empty array to render component on only mounting and unmounting.

                  3. Use Multiple useEffect() hooks to Separate Concerns and react will:



                  Hooks lets us split the code based on what it is doing rather than a lifecycle method name. React will apply every effect used by the component, in the order they were specified






                  Using Classes:



                  class Example extends React.Component {
                  constructor(props) {
                  super(props);
                  this.state = {
                  count: 0
                  };
                  }

                  componentDidMount() {
                  document.title = `You clicked ${this.state.count} times`;
                  }

                  componentDidUpdate() {
                  document.title = `You clicked ${this.state.count} times`;
                  }

                  render() {
                  return (
                  <div>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.setState({ count: this.state.count + 1 })}>
                  Click me
                  </button>
                  </div>
                  );
                  }
                  }


                  Using Hooks:



                  import { useState, useEffect } from 'react';

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

                  // Similar to componentDidMount and componentDidUpdate:
                  useEffect(() => {
                  // Update the document title using the browser API
                  document.title = `You clicked ${count} times`;
                  });

                  return (
                  <div>
                  <p>You clicked {count} times</p>
                  <button onClick={() => setCount(count + 1)}>
                  Click me
                  </button>
                  </div>
                  );
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 29 at 19:24

























                  answered Oct 29 at 18:32









                  Sakhi Mansoor

                  2,3422417




                  2,3422417






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53051465%2freact-hooks-what-why-useeffect%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

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      Refactoring coordinates for Minecraft Pi buildings written in Python