Need for it
- Side Effects: Manage side effects like data fetching, event subscriptions, or DOM manipulations in functional components.
- Lifecycle Management: Replace lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount) in class components.
What is it
- useEffect Hook: A React built-in function used in functional components to handle side effects after rendering or when dependencies change.
How is it used in the real world
- Fetching Data: Use useEffect to fetch data from APIs asynchronously after component rendering.
- Event Handling: Subscribe to and unsubscribe from events dynamically based on component lifecycle.
- Cleanup: Perform cleanup tasks like removing event listeners to prevent memory leaks.
Example:
import React, { useEffect } from 'react'; const MyComponent = () => { useEffect(() => { // Code to be executed after component has rendered // Fetch data from an API fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { // Do something with the data }); // Subscribe to an event const eventListener = () => { // Handle the event }; window.addEventListener('click', eventListener); // Clean up the side effect return () => { window.removeEventListener('click', eventListener); }; }, []); // Empty dependency array means the effect runs only once return ( <div> {/* Component JSX */} </div> ); }; export default MyComponent;
In real-world applications, the useEffect hook is essential for managing asynchronous tasks, event handling, and cleanup operations in React functional components, providing flexibility and clarity in component lifecycle management.