useEffect

Basics

  • Runs after every re-render
  • It takes the callback function
    • useEffect(() => {});
  • This is not allowed
    •    if (true) {
          useEffect(() => {});
        }
  • Multiple use effect is possible – output in the below screenshot
    •   useEffect(() => {
          console.log(“hello”);
        }, []);

       

        useEffect(() => {
          console.log(“hello-world”);
        }, []);
  •  

Dependency Array

  • The second parameter is dependency array
    •   useEffect(() => {
          console.log(“hello-world”);
        }, []);
  • As it is empty array – it will only render once.
  • But if you see in other useEffect it takes counter. On every button click the counter value changes, which re-renders the component. The other useEffect will be called.
    •  useEffect(() => {
          console.log(“hello”);
        }, [counter]);
				
					import React, { useEffect, useState } from "react";

const UseEffectBasics = () => {
  const [counter, setCounter] = useState(0);

  useEffect(() => {
    console.log("hello");
  }, [counter]);

  useEffect(() => {
    console.log("hello-world");
  }, []);

  return (
    <>
      <div className="myClass">
        <ul>
          <li>{counter}</li>
          <button onClick={() => setCounter(counter + 1)}> Click</button>
        </ul>
      </div>
    </>
  );
};
export default UseEffectBasics;

				
			
  • The first hello and hello-world is on initial render
  • Then 21 clicks –> 21 hello

Leave a Comment