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 (
<>
- {counter}
>
);
};
export default UseEffectBasics;
DATA
- The first hello and hello-world is on initial render
- Then 21 clicks –> 21 hello
![](https://clientsidecoding.com/wp-content/uploads/2023/01/t3-6.jpg)