The useEffect hook in React is essential for handling side effects in functional components, such as data fetching, DOM updates, or subscriptions. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount used in class components.
Basic Syntax
useEffect takes two arguments:
- A function:Contains the side effect logic.
- An optional dependency array:Controls when the effect runs.
The effect runs on initial render and when dependencies change. If no dependency array is provided, it runs after every render.
Example: Data Fetching
Cleanup with useEffect
You can return a cleanup function to clear side effects, like timers or subscriptions, before the component unmounts.
Effects with Dependencies
You can trigger effects based on state or prop changes by listing them in the dependency array.
Best Practices
- Clean up side effects to avoid memory leaks.
- Limit unnecessary re-renders by carefully managing the dependency array.
- Use multiple effects if needed to keep logic clear.
The useEffect hook simplifies handling side effects in functional components, making it easier to manage data fetching, DOM manipulation, and more.