useEffect is a react hook used to handle sideeffect in functional component.It allows us to execute code after rendering based on the dependency array.
Syntax of useeffect()
import React, { useEffect } from 'react';
useEffect(() => {
// Side effect code
}, []);
Callback function: Contains the code that should execute.
Dependency array: Determines when the effect should execute again.
There are 3 common ways to use useEffect, based on the dependency array.
Type 1-Without dependency array
ex:-useEffect(() => {
console.log("Hello");
});
- Executes after every render.
- Whenever state changes and the component renders again, it executes.
Type 2-With empty dependency array []
ex:-useEffect(() => {
console.log("Hello");
}, []);
- Executes after the initial render.
- Does not execute again on normal re-renders.
Type 3-With dependency array [count]
ex:-useEffect(() => {
console.log("Count changed");
}, [count]);
- Executes after the initial render.
- Executes again whenever count changes.
