Add useUnmountCleanupRef custom hook to centralize and simplify unmount cleanup logic in document page components. Refactor EPUB, HTML, and PDF page components to utilize this hook, replacing repetitive ref and effect patterns for invoking cleanup functions on unmount. This reduces code duplication and improves maintainability.
19 lines
394 B
TypeScript
19 lines
394 B
TypeScript
import { useEffect, useRef } from 'react';
|
|
|
|
/**
|
|
* Runs cleanup only on unmount, while always invoking the latest cleanup function.
|
|
*/
|
|
export function useUnmountCleanupRef(cleanup: () => void) {
|
|
const cleanupRef = useRef(cleanup);
|
|
|
|
useEffect(() => {
|
|
cleanupRef.current = cleanup;
|
|
}, [cleanup]);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
cleanupRef.current();
|
|
};
|
|
}, []);
|
|
}
|
|
|