File size: 525 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { useCallback, useRef, useLayoutEffect } from 'react';

/**
 * Hook to be used to make sure a function `fn` is called only
 * if the component which uses it is still mounted.
 * @param {Function} fn A function you want to be safe to call
 */
export default function useSafe( fn ) {
	const mounted = useRef( false );

	useLayoutEffect( () => {
		mounted.current = true;
		return () => ( mounted.current = false );
	}, [] );

	return useCallback( ( ...args ) => ( mounted.current ? fn( ...args ) : void 0 ), [ fn ] );
}