useEffect with Variation example in react js
useEffect-: is used to perform side effects in our component, side effects are those actions which are performed with the outside world, side effect perform when we need to reach outside of our React components to do some task eg: updating DOM , Fetching the API data , timer functions like setTimeout , setInterval
useEffect function contain callback function for side effect login and dependencies (array of variables)
useEffect(callback, dependencies which is optional)
useEffect Variation:-
a) useEffect without dependencies
b) useEffect with empty array
c) useEffect with variables
Example of useEffect without dependencies
useEffect will run everytime when useState variable value change
import React, { useState, useEffect } from 'react';
const App = () =>{
const [count, setCount] = useState(0)
useEffect(() => {
document.title = `${count} Title using React`;
});
return (
<>
<p>{count} Title using React</p>
<button onClick={() => setCount(count+1)}>Increase</button>
</>
)
}
export default App;
Code Explanation:
Import react useState and useEffect
import React, { useState, useEffect } from 'react';
Initialize useState with state function and variable
const [count, setCount] = useState(0)
Define useEffect: define useEffect function in which we are changes the web page title with useState variable value
Call useState function:
call useState function using onClick event and render variable value
<p>{count} Title using React</p>
<button onClick={() => setCount(count+1)}>Increase</button>
Example of useEffect with empty array
with empty array useEffect it will run only once, only when componet get render first time so it is usefull when we want to fetch api data and want to render once
import React, { useState, useEffect } from 'react';
const App = () =>{
const [count, setCount] = useState(0)
useEffect(() => {
document.title = `${count} Title using React`;
},[]);
return (
<>
<p>{count} Title using React</p>
<button onClick={() => setCount(count+1)}>Increase</button>
</>
)
}
export default App;
Output:
Example of useEffect with variables:
we have to pass variable with useEffect it will run once the variable value change.
import React, { useState, useEffect } from 'react';
const App = () =>{
const [count, setCount] = useState(0)
const [otherCount, setOtherCount] = useState(2)
useEffect(() => {
document.title = `${otherCount} useEffect with variables`;
},[otherCount]);
return (
<>
<p>{count} Title using React</p>
<button onClick={() => setCount(count+1)}>Increase</button>
<p>{otherCount} useEffect with variables</p>
<button onClick={() => setOtherCount(otherCount + 2)}> Increase by 2</button>
</>
)
}
export default App;
Output:
Keep Learning 🙂