Explain the purpose of the useEffect hook in React
Answer
The useEffect hook allows you to perform side effects in functional components. It can replace lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. Common use cases:
- Fetching data from an API.
- Adding event listeners.
- Cleaning up subscriptions or resources.
useEffect(() => {
// Side effect logic here
return () => {
// Cleanup logic here
};
}, [dependencies]);
The dependencies array controls when the effect runs. Leaving it empty runs the effect once after the initial render.