JAVASCRIPT
Manage Component Lifecycle for External Subscriptions
Create a custom React hook to simplify subscribing and unsubscribing from external data sources or events, ensuring proper cleanup on unmount.
import { useEffect, useRef } from 'react';
/**
* A custom hook to manage subscriptions to external services,
* ensuring proper setup and cleanup.
*
* @param {function} subscribeFn - A function that returns an unsubscribe function.
* @param {Array} dependencies - Dependencies array for useEffect.
*/
function useSubscription(subscribeFn, dependencies = []) {
const unsubscribeRef = useRef(null);
useEffect(() => {
// Subscribe
const unsubscribe = subscribeFn();
unsubscribeRef.current = unsubscribe;
// Return cleanup function
return () => {
if (typeof unsubscribeRef.current === 'function') {
unsubscribeRef.current();
}
};
}, dependencies); // eslint-disable-line react-hooks/exhaustive-deps
}
export default useSubscription;
How it works: This `useSubscription` hook offers a clean pattern for interacting with external services that require explicit subscription and unsubscription. The `useEffect` hook ensures that the `subscribeFn` is called when the component mounts (or dependencies change) and its returned cleanup function is invoked when the component unmounts. This prevents memory leaks and ensures resource management, making it ideal for WebSocket connections, event listeners, or other observable patterns.