From 3305f39c51c63fed78a84869b5771f9cd5a99ec0 Mon Sep 17 00:00:00 2001 From: jeetiss Date: Fri, 14 Jun 2019 22:18:22 +0300 Subject: [PATCH 1/2] save callback independently add deps for skip useless event sub/unsub --- src/useClickAway.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/useClickAway.ts b/src/useClickAway.ts index b5788863ef..23933b546f 100644 --- a/src/useClickAway.ts +++ b/src/useClickAway.ts @@ -1,4 +1,4 @@ -import { RefObject, useEffect } from 'react'; +import { RefObject, useEffect, useRef } from 'react'; import { off, on } from './util'; const defaultEvents = ['mousedown', 'touchstart']; @@ -8,10 +8,14 @@ const useClickAway = ( onClickAway: (event: KeyboardEvent) => 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; From 8fb58957b6e711ba44c4edc2450e40b94d1eee8a Mon Sep 17 00:00:00 2001 From: jeetiss Date: Fri, 14 Jun 2019 22:18:47 +0300 Subject: [PATCH 2/2] don't use alert in story --- docs/useClickAway.md | 2 +- src/__stories__/useClickAway.story.tsx | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) 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 (