⭐useEffect in React

We setup useEffect hook to run some code WHEN.

πŸ‘‰ Component renders for the (First Time)

πŸ‘‰ WHENEVER its re-renders

πŸ‘‰ When Some data in our component changed.

Import useEffect at first

import { useEffect, useState } from "react";

πŸ—οΈ Type - 1: (Without the empty array)

const App = () => {
  const [value, setValue] = useState(0);
  useEffect(() => {
    console.log("call useEffect");
    document.title = `Increment (${value})`;
  });

  return (
    <>
      <h2>{value}</h2>
      <button onClick={() => setValue(value + 1)}>Click me</button>
    </>
  );
};

πŸ—οΈ Type - 2: (Conditional)

You cannot wrap hook with conditional statement but if you want logic, you'll have to put it inside your hook.

✨ Type - 3: (Dependency + Re-rendering when value changes)

Empty array means (it will ONLY run on initial render) ..passing value to array means (it will re-render when that value changed)

✨ Type - 4: (Component renders for the First Time or Fetching data before showing to component)

🌱 Type - 5: (These cleanups can prevent memory leaks and remove unwanted things.)

Last updated