openreader/src/hooks/useUnmountCleanupRef.ts
Richard R 3db193e012 feat(hooks): introduce useUnmountCleanupRef for effect cleanup abstraction
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.
2026-05-27 16:22:14 -06:00

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();
};
}, []);
}