useEffect Hook in React.js

What is use of useEffect


Remove side effect inside component

Remove side effect from outside component

Use to fetch data

Can use as life cycle methods

Can use for DOM manipulation

Much More


Basic use of useEffect

Prevents extra rendering of the component on state changes

Very important for interviews


Basic Syntax of useEffect:

useEffect(() => {
// your side effect code here
}, [dependencies]);


Example

function callOnce() {
console.log("callOnce function called");
}

callOnce();

return (
<div>
<h1>useEffect Hook</h1>
<button onClick={() => setCount(count + 1)}>Count {count}</button>
</div>
);


  1. Whenever the button is clicked, the count will increase by 1 and callOnce function will be called again and again.
  2. To control this behavior and run the function only once, we can use the useEffect hook.


useEffect(() => {
callOnce(); // only runs once when the component mounts
}, []);


Call a function inside useEffect based on a state

function counterFunction() {
console.log(counter);
} // Want this function to be called only when counter updates

useEffect(() => {
counterFunction();
}, [counter]);


Handling Dependencies

Call every time

useEffect(() => {
// called every time component renders
});


Call only once

useEffect(() => {
// called only once when component mounts
}, []);


Call when a single state changes

useEffect(() => {
// called when state1 changes
}, [state1]);


Call when both states change

useEffect(() => {
// called when state1 or state2 changes
}, [state1, state2]);


Call when props change

useEffect(() => {
// called when prop1 changes
}, [prop1]);

useEffect(() => {
// called when prop2 changes
}, [prop2]);


Multiple useEffect hooks

You can use more than one useEffect in the same component.

This helps you separate concerns and run different pieces of logic based on different dependencies.