From 390d2bfb05a5989a95947a4abcf4ea33baf2e917 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Bourgier?= Date: Sat, 22 Feb 2020 14:23:37 +0100 Subject: [PATCH] Reset inView and entry when observed component is unmounted Fix #303 --- src/__tests__/hooks.test.js | 22 ++++++++++++++++++++++ src/useInView.tsx | 6 ++++++ 2 files changed, 28 insertions(+) diff --git a/src/__tests__/hooks.test.js b/src/__tests__/hooks.test.js index 35367924..d3d54434 100644 --- a/src/__tests__/hooks.test.js +++ b/src/__tests__/hooks.test.js @@ -27,6 +27,17 @@ const LazyHookComponent = ({ options }) => { ) } +const UnmountableRefComponent = ({ mount }) => { + const [ref, inView] = useInView() + + return ( + <> + {mount &&
} + {inView.toString()} + + ) +} + test('should create a hook', () => { const { getByTestId } = render() const wrapper = getByTestId('wrapper') @@ -74,3 +85,14 @@ test('should unmount the hook', () => { unmount() expect(instance.unobserve).toHaveBeenCalledWith(wrapper) }) + +test('inView should be false when component is unmounted', () => { + const { rerender, getByText } = render( + , + ) + mockAllIsIntersecting(true) + + getByText('true') + rerender() + getByText('false') +}) diff --git a/src/useInView.tsx b/src/useInView.tsx index a597542a..5a3ab597 100644 --- a/src/useInView.tsx +++ b/src/useInView.tsx @@ -43,6 +43,12 @@ export function useInView( [options.threshold, options.root, options.rootMargin, options.triggerOnce], ) + React.useLayoutEffect(() => { + if (!ref.current && state.inView) { + setState({ inView: false, entry: undefined }) + } + }) + React.useDebugValue(state.inView) return [setRef, state.inView, state.entry]