React - useEffect hook with example

As we have seen useState earlier, In this article, we will look at useEffect hook.

    useEffect

      Like useState or every other hook, useEffect is a function. it takes 2 parameters, first is a callback function and second is the dependency list, which we will see in detail later in this post.

      This hook allows to perform side-effects, meaning that it permits to perform any activies outside component execution.

      By default, useEffect runs after every re-render.

      It can be used for dependent data fetching or any other asynchronous, background tasks.

      We can have multiple useEffect in the same component. Their order of execution is order of declaration. We can create side effects for below operations:

      • Conditional rendering
      • AJAX calls
      • Dependency management
      • Perform cleanup activities


      Lets look at an example:


        import React, { useState, useEffect } from "react";
        import ReactDOM from "react-dom";
        import "./styles.css";

        const ReactLifecycle = () => {
          console.log("Rendering ReactLifecycle component.");
          const [clickCount, setClickCount] = useState(0);

          const [person, setPerson] = useState({
            id: 1,
            name: "Hardik",
            message: "Default Message",
          });

          const incrementHandler = (event, name) => {
            console.log("clickCount is incremented by One...");
            const newClickCount = clickCount + 1;
            setClickCount(newClickCount);

            setPerson({
              ...person,
              message: `Hello, from ${person.name}`,
            });
          };

          const resetHandler = () => {
            console.log("clickCount is reset to Zero..");
            const newClickCount = 0;
            setClickCount(newClickCount);
          };

          //useEffect method 1
          useEffect(() => {
            console.log("useEffect1 is called");
          });

          //useEffect method 2
          useEffect(() => {
            console.log("useEffect2 is called");
          });

          return (
            <>
              <h1>
                {person.message}, total clicks are {clickCount}
              </h1>
              <button className="btn" onClick={(event) => incrementHandler()}>
                Click Now to increment!
              </button>
              <button className="btn" onClick={(event) => resetHandler()}>
                Reset Count!
              </button>
            </>
          );
        };

        const rootElement = document.getElementById("root");
        ReactDOM.render(<ReactLifecycle />, rootElement);





      useEffect is a function which takes a callback function as a parameter. We have added an arrow function which will be called after the component is rendered. 

      Also notice that we can have multiple useEffects as can be seen below, their order of execution is defined by order of their declaration. performed.

      Output:



      Using dependency list

      In addition to the handler or callback function, we can limit useEffect's execution to conditional execution.


        //useEffect method 1
        useEffect(() => {
          console.log("useEffect1 is called");
        }, []); //passing empty array as dependency


      By passing an empty array, useEffect method will run only once.


          //useEffect method 1, if we pass empty array,
          //it will run only once when component renders
          useEffect(() => {
          console.log("useEffect1 is called");
          }, []);


      If we pass value or dependency list in the empty array, say person.message, it will run only when the value of person.message changes.


          //useEffect method 2
          useEffect(() => {
          console.log("useEffect2 is called only when person.message value changes!");
          }, [person.message]);

          const changeMessage = () =>
          setPerson({
              ...person,
              message:
              person.message === `Hello, from ${person.name}`
                  ? "Default Message"
                  : `Hello, from ${person.name}`,
          });


      My making above tweaks in our code, the behavior is:

      • When component renders, useEffect1 and useEffect2 are called
      • When we increment the number from 0 to 1, as person.message value changes, useEffect2 is called but not useEffect1
      • After subsequent increments, neither of useEffect1 or useEffect2 are called
      • When we click on change message button, it works as a toggle (refer above code) hence every time its clicked, only useEffect2 is called.
      • On click of reset count, neither useEffect1 or useEffect2 are called. But when we increment the count, again only useEffect2 is called and cycle continues.














          In addition to above, useEffect can also be used for cleanup activities, such as removing event listeners, calling APIs on user logout etc.



          Comments

          Popular Posts