Unsubscribing from a Data Fetching Library in useEffect
Showcase using useEffect in React 18 to automatically unsubscribe from a data subscription to avoid memory leaks when a component unmounts.
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Imagine we have a library DataFetcher providing subscription to data changes
const subscription = DataFetcher.subscribe();
// Subscribe to some data updates when component mounts
subscription.on('data', handleData);
// Specify how to clean up after this effect:
return function cleanup() {
// Unsubscribe when the component unmounts to prevent memory leaks
subscription.off('data', handleData);
};
}, []); // Empty dependency array means this effect runs once on mount and cleanup on unmount
function handleData(data) {
// Handle the data
console.log(data);
}
return (
// Your component JSX goes here
);
}
export default MyComponent;
This code showcases a React component utilizing useEffect to subscribe to a data fetching service when the component mounts and automatically unsubscribing when the component unmounts to avoid memory leaks. The subscription uses 'on' to listen for 'data' events, and the cleanup function is provided to detach the event listener with 'off'. The useEffect hook is provided with an empty dependency array to ensure it runs only once during the component's lifecycle.