useEffect is a hook used to perform side effects in function components. If you need to use multiple useEffect hooks in a single component, you can simply place them one after the other within your component function.
Key Points for Using Multiple useEffect Hooks:
- Separation of Concerns: Each
useEffecthook should handle a specific side effect or concern. This helps to keep your code organized and easier to understand. - Order Matters: The order in which you define
useEffecthooks within your component matters. They will be executed in the same order as they are declared. - Dependency Arrays: Each
useEffectcan have its dependency array, which specifies when the effect should run. If the dependency array is empty ([]), the effect runs only once when the component mounts. If you provide dependencies, the effect runs whenever any of those dependencies change. - Dependencies Management: Be careful with dependencies to prevent unnecessary re-renders or side effects. Ensure that you include only the necessary dependencies for each
useEffecthook. - Readability: Keep your code readable by placing each
useEffecthook logically in relation to the component's behavior. If one effect depends on another, consider placing them close together.
Example: Below is an example of using multiple useEffect in a component. The Timer component utilizes two useEffect hooks: one manages a timer based on the isActive state, while the other triggers an alert at 10 seconds, each with their specific dependencies, alongside functions to control the timer.
import React, {
useState,
useEffect
} from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
const [isActive, setIsActive] = useState(false);
useEffect(() => {
console.log("Timer isActive changed:", isActive);
let intervalId;
if (isActive) {
intervalId = setInterval(() => {
setSeconds((prevSeconds) =>
prevSeconds + 1);
}, 1000);
}
return () => {
console.log("Timer cleanup, isActive:",
isActive);
clearInterval(intervalId);
};
}, [isActive]);
useEffect(() => {
console.log("Timer seconds changed:",
seconds);
if (seconds >= 10) {
alert('Timer reached 10 seconds!');
setIsActive(false);
}
}, [seconds]);
const startTimer = () => {
setIsActive(true);
};
const stopTimer = () => {
setIsActive(false);
};
const resetTimer = () => {
setSeconds(0);
setIsActive(false);
};
return (
<div>
<h2>Timer: {seconds} seconds</h2>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
<button onClick={resetTimer}>Reset</button>
</div>
);
}
export default Timer;
Output:
