mirror of
https://github.com/dergigi/boris.git
synced 2026-01-17 13:54:24 +01:00
- Create useMountedState hook to track component mount status - Refactor useArticleLoader to use shared hook - Refactor useExternalUrlLoader to use shared hook - Remove duplicated isMounted pattern across both loaders - Cleaner, more DRY code with same functionality
29 lines
610 B
TypeScript
29 lines
610 B
TypeScript
import { useRef, useEffect, useCallback } from 'react'
|
|
|
|
/**
|
|
* Hook to track if component is mounted and prevent state updates after unmount.
|
|
* Returns a function to check if still mounted.
|
|
*
|
|
* @example
|
|
* const isMounted = useMountedState()
|
|
*
|
|
* async function loadData() {
|
|
* const data = await fetch(...)
|
|
* if (isMounted()) {
|
|
* setState(data)
|
|
* }
|
|
* }
|
|
*/
|
|
export function useMountedState(): () => boolean {
|
|
const mountedRef = useRef(true)
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
mountedRef.current = false
|
|
}
|
|
}, [])
|
|
|
|
return useCallback(() => mountedRef.current, [])
|
|
}
|
|
|