diff --git a/docs/useClickAway.md b/docs/useClickAway.md index 1231909080..84f83cabdb 100644 --- a/docs/useClickAway.md +++ b/docs/useClickAway.md @@ -12,7 +12,7 @@ import {useClickAway} from 'react-use'; const Demo = () => { const ref = useRef(null); useClickAway(ref, () => { - alert('OUTSIDE CLICKED'); + console.log('OUTSIDE CLICKED'); }); return ( diff --git a/src/__stories__/useClickAway.story.tsx b/src/__stories__/useClickAway.story.tsx index 9f7c2dd653..67c8c75a36 100644 --- a/src/__stories__/useClickAway.story.tsx +++ b/src/__stories__/useClickAway.story.tsx @@ -1,3 +1,4 @@ +import { action } from '@storybook/addon-actions'; import { storiesOf } from '@storybook/react'; import * as React from 'react'; import { useRef } from 'react'; @@ -6,9 +7,7 @@ import ShowDocs from './util/ShowDocs'; const Demo = () => { const ref = useRef(null); - useClickAway(ref, () => { - alert('OUTSIDE CLICKED'); - }); + useClickAway(ref, action('outside clicked')); return (
void, events: string[] = defaultEvents ) => { + const savedCallback = useRef(onClickAway); + useEffect(() => { + savedCallback.current = onClickAway; + }, [onClickAway]); useEffect(() => { const handler = event => { const { current: el } = ref; - el && !el.contains(event.target) && onClickAway(event); + el && !el.contains(event.target) && savedCallback.current(event); }; for (const eventName of events) { on(document, eventName, handler); @@ -21,7 +25,7 @@ const useClickAway = ( off(document, eventName, handler); } }; - }); + }, [events, ref]); }; export default useClickAway;