β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