React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
When and how often does React invoke the setup and cleanup functions inside a useEffect hook?
- Setup Function Execution (
useEffect)
The setup function (or the main function) you pass to useEffect runs at specific points:
markdown
1. **After the component is mounted** (if the dependency array is empty `[]`)
2. **After every render** (if no dependency array is provided)
3. **After a dependency value changes** (if the dependency array contains variables)
2. Cleanup Function Execution (Returned function from useEffect)
The cleanup function is called before the effect is re-executed and when the component unmounts.
Practical Code Example
jsx
// Setup and Cleanup lifecycle:
useEffect(() => {
const id = setInterval(tick, 1000); // Setup: runs on mount & when deps change
return () => clearInterval(id); // Cleanup: runs before next effect & on unmount!
}, []);