Author: M Abo Bakar Aslam
useEffect Hook
11:00Before continuing this lesson, you can download the starting code by using the button below. In the code, you can easily run examples of this lesson.
The useEffect() function is automatically executed when a component completes its rendering. In other words, it runs after the component returns its TSX/JSX.
The useEffect() function takes two parameters:
- A callback function (first parameter)
- A dependency array (second parameter)
1. Empty Dependency
When the dependency array is empty ([]), the useEffect() function runs only once after the component is rendered for the first time.
In this case, you can use it for tasks like:
- States initialization
- Logging messages
- Initial API calls
- Initial setup operations
Example 1: Display simple string data in the console window when the App component completes its rendering.
- Line 3: The useEffect is imported from react
- Line 7-9: The useEffect is called and its body is defined having console's output.
- Line 9: empty dependency in useEffect because there is nothing in second parameter ( [ ] )
// File: App.tsx located in app-name/src/
import { useEffect } from "react";
export default function App() {
useEffect(() => {
console.log("useEffect function is callled");
}, []); //empty dependency
return (
<div>
<h1>useEffect Explanation</h1>
</div>
);
}2. Delay using setTimeout()
The setTimeout() function is used to delay execution of certain code.
It takes two parameters:
- First Paramter: A callback function
- Second Paramter: Time delay in milliseconds
This is useful when you want to perform an action after a specific delay.
Example 2: Add some lines in previous example such that that lines will be executed after some delay.
- Line 10-13: The setTimeout( ) function is called.
- Line 13: The delay is set as 3 seconds (3000 milliseconds)
// File: App.tsx located in app-name/src/
import { useEffect } from "react";
export default function App() {
useEffect(() => {
console.log("useEffect function is callled");
//delayed execution
setTimeout(() => {
console.log("delayed output");
}, 3000); // 3 seconds delay
}, []); //empty dependency
return (
<div>
<h1>useEffect Explanation</h1>
</div>
);
}4. Updating State with setTimeout()
You can combine useEffect() with setTimeout() to update state variables after a delay.
In this approach:
- A state variable is created using
useState - Inside
useEffect(),setTimeout()is used - After a specific time, the state is updated automatically
This technique is commonly used for:
- Loading messages
- Splash screens
- Update UI after sometimes
Example 3: We updated example-code-2 and used useState instead of simple-console.
- Line 3: The useState is imported
- Line 7-8: The state is defined and initialized.
- Line 15: The state is update in useEffect ( ) and setTimeout ( ) functions.
- Line 22: The state is displayed in TSX/JSX.
// File: App.tsx located in app-name/src/
import { useEffect, useState } from "react";
export default function App() {
const [myState, setmyState] = useState(
"Are you ready to understand useEffect and setTimeout?"
);
useEffect(() => {
console.log("useEffect function is callled");
//delayed execution
setTimeout(() => {
setmyState("Ready");
}, 5000); // 5 seconds delay
}, []); //empty dependency
return (
<div>
<h1>useEffect Explanation</h1>
<br />
<p>{myState}</p>
</div>
);
}5. Multiple setTimeout() Functions
If you want to perform multiple delayed actions:
- Use multiple
setTimeout()functions when delay times are different - If delay time is the same, it is better to combine logic into one function
Although multiple timers can be used, it is recommended to keep the logic simple and organized.
Example 4: Combine above two example such that multiple setTimeout functions are used. One function is used for simple-console and other is used for state-variable.
- Line 15-17: Three-seconds delayed function
- Line 19-21: Five-second delayed function.
// File: App.tsx located in app-name/src/
import { useEffect, useState } from "react";
export default function App() {
const [myState, setmyState] = useState(
"we are creating states in useEffect and setTimeOut. Are you ready to understand..."
);
useEffect(() => {
console.log("useEffect function is callled");
//delayed execution
// 3 seconds
setTimeout(() => {
console.log("3 seconds delayed");
}, 3000);
// 5 seconds
setTimeout(() => {
setmyState("Ready");
}, 5000); // 5 seconds delay
}, []); //empty dependency
return (
<div>
<h1>useEffect Explanation</h1>
<br />
<p>{myState}</p>
</div>
);
}6. Dependency in useEffect
The dependency array controls when useEffect() runs.
If you include a variable (e.g., a state variable) in the dependency array:
- The
useEffect()function will run whenever that variable changes
This is useful when:
- You want to respond to user actions
- You want to trigger logic based on state updates
Example 5: Do following task in this example.
- Create a button in TSX
- When click on the button, then a function should be called. Display any text in console-window when the function is called.
- Define a state named as count and initialize it by 0.
- Display value of count in JSX below the button.
- Increment the value of count by one whenever the button is clicked (the function is called).
- Create useEffect( ) function having dependency on count. Display something when the function is called when value of count is changed.
Solution
- Line 25-30: Button is created
- Line 11-14: A function is called when button is clicked and a text is displayed in console-window.
- Line 8: state-variable count is create
- Line 32: The value of count is displayed in TSX/JSX
- Line 13: The value of count is incremented by 1, when button is clicked (respective function is called)
- Line 17-19: useEffect with dependency on count state.
// File: App.tsx located in app-name/src/
import { useEffect, useState } from "react";
export default function App() {
//defining count state
const [count, setcount] = useState(0);
//defining function for button
const plusCount = () => {
console.log("Button is clicked");
setcount(count + 1);
};
//useEffect with dependency
useEffect(() => {
console.log("called->dependent useEffect");
}, [count]);
return (
<div>
<h1>useEffect Explanation</h1>
<br />
<button
onClick={plusCount}
style={{ backgroundColor: "red", color: "white", padding: "12px" }}
>
Click Me
</button>
<p>
<b>Number of clicks on the button:</b> {count}
</p>
</div>
);
}7. Multiple useEffect() Functions
You can define more than one useEffect() in a single component.
For example:
- One
useEffect()can run only once (empty dependency) - Another
useEffect()can run when a specific variable changes
This helps in separating logic and improving code readability.
Example 6: We combined above examples such that multiple useEffect( ) functions are used. One is based on dependency and other is with empty dependency.
// File: App.tsx located in app-name/src/
import { useEffect, useState } from "react";
export default function App() {
const [myState, setmyState] = useState(
"Are you ready to understand useEffect and setTimeout?"
);
//defining count state
const [count, setcount] = useState(0);
//defining function for button
const plusCount = () => {
console.log("Button is clicked");
setcount(count + 1);
};
// useEffect with empty-dependency
useEffect(() => {
console.log("useEffect function is callled");
//delayed execution
// 3 seconds
setTimeout(() => {
console.log("3 seconds delayed");
}, 3000);
// 5 seconds
setTimeout(() => {
setmyState("Ready");
}, 5000); // 5 seconds delay
}, []); //empty dependency
//useEffect with dependency
useEffect(() => {
console.log("called->dependent useEffect");
}, [count]);
return (
<div>
<h1>useEffect Explanation</h1>
<br />
<p>{myState}</p>
<button
onClick={plusCount}
style={{ backgroundColor: "red", color: "white", padding: "12px" }}
>
Click Me
</button>
<p>
<b>Number of clicks on the button:</b> {count}
</p>
</div>
);
}8. Multiple Dependencies in useEffect
You can include multiple variables in the dependency array.
In this case:
- The
useEffect()function runs if any one of the dependencies changes
This works like an OR condition.
Alternatively, you can:
- Use multiple
useEffect()functions with separate dependencies - Or use a single
useEffect()with multiple dependencies
Example 7: Create a button that will decrement the value whenever click on the button. This example is just like above example but here we added another button and state for decrement.
// File: App.tsx located in app-name/src/
import { useEffect, useState } from "react";
export default function App() {
//defining count state
const [count, setcount] = useState(0);
const [deccountstate, setdeccoutstate] = useState(0);
//defining function for plus button
const plusCount = () => {
console.log("plus Button is clicked");
setcount(count + 1);
};
//defining function for decrement button
const decCount = () => {
console.log("decrement Button is clicked");
setdeccoutstate(deccountstate - 1);
};
//useEffect with dependency
useEffect(() => {
console.log("called->dependent useEffect");
}, [count, deccountstate]);
return (
<div>
<h1>useEffect Explanation</h1>
<br />
<button
onClick={plusCount}
style={{
backgroundColor: "red",
color: "white",
padding: "12px",
marginRight: "8px",
cursor: "pointer",
}}
>
Increment by 1
</button>
<button
onClick={decCount}
style={{
backgroundColor: "red",
color: "white",
padding: "12px",
cursor: "pointer",
}}
>
Decrement By 1
</button>
<p>
<b>Total Plus:</b> {count}
</p>
<p>
<b>Total Decrement:</b> {deccountstate}
</p>
</div>
);
}