Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/__tests__/hooks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ const LazyHookComponent = ({ options }) => {
)
}

const UnmountableRefComponent = ({ mount }) => {
const [ref, inView] = useInView()

return (
<>
{mount && <div ref={ref} />}
{inView.toString()}
</>
)
}

test('should create a hook', () => {
const { getByTestId } = render(<HookComponent />)
const wrapper = getByTestId('wrapper')
Expand Down Expand Up @@ -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(
<UnmountableRefComponent mount={true} />,
)
mockAllIsIntersecting(true)

getByText('true')
rerender(<UnmountableRefComponent mount={false} />)
getByText('false')
})
6 changes: 6 additions & 0 deletions src/useInView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down