Q1. What is the useEffect hook?
useEffect is a React hook that lets you perform side effects in functional components. It takes a function (effect) and a dependency array. The effect runs after the render. You can use it for data fetching, subscriptions, timers, or manually changing the DOM.
Q2. How does useEffect work?
By default, useEffect runs after every completed render (both mount and update). You can control when it runs by passing a dependency array. If the array is empty, the effect runs only once after the initial render. If dependencies are listed, it runs whenever any dependency changes.
Q3. How do you clean up with useEffect?
To clean up, return a function from the effect. This cleanup function runs before the component unmounts and before re-running the effect (if dependencies change). It's used for removing event listeners, canceling subscriptions, etc.
Q4. What happens if you don't provide a dependency array?
If you omit the dependency array, the effect runs after every render (including initial and every update). This can cause performance issues or infinite loops if the effect updates state. Usually you want to specify dependencies to control execution.
Q5. Can you use multiple useEffect hooks?
Yes, you can use multiple useEffect hooks to separate concerns. For example, one effect for fetching data and another for setting up event listeners. React will apply them in the order they are declared.
