Skip to content

Commit 0c450ce

Browse files
authored
bugfix: fix #303 (#306)
1 parent 211228a commit 0c450ce

File tree

3 files changed

+22
-9
lines changed

3 files changed

+22
-9
lines changed

src/InView.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,10 @@ export class InView extends React.Component<
8484
}
8585

8686
handleNode = (node?: Element | null) => {
87-
if (this.node) unobserve(this.node)
87+
if (this.node) {
88+
unobserve(this.node)
89+
if (!node) this.setState({ inView: false, entry: undefined })
90+
}
8891
this.node = node ? node : null
8992
this.observeNode()
9093
}

src/__tests__/hooks.test.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import { render } from '@testing-library/react'
33
import { useInView } from '../useInView'
44
import { intersectionMockInstance, mockAllIsIntersecting } from '../test-utils'
55

6-
const HookComponent = ({ options }) => {
6+
const HookComponent = ({ options, unmount }) => {
77
const [ref, inView] = useInView(options)
88
return (
9-
<div data-testid="wrapper" ref={ref}>
9+
<div data-testid="wrapper" ref={!unmount ? ref : undefined}>
1010
{inView.toString()}
1111
</div>
1212
)
@@ -74,3 +74,12 @@ test('should unmount the hook', () => {
7474
unmount()
7575
expect(instance.unobserve).toHaveBeenCalledWith(wrapper)
7676
})
77+
78+
test('inView should be false when component is unmounted', () => {
79+
const { rerender, getByText } = render(<HookComponent />)
80+
mockAllIsIntersecting(true)
81+
82+
getByText('true')
83+
rerender(<HookComponent unmount />)
84+
getByText('false')
85+
})

src/useInView.tsx

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,22 @@ type State = {
88
entry?: IntersectionObserverEntry
99
}
1010

11+
const initialState: State = {
12+
inView: false,
13+
entry: undefined,
14+
}
15+
1116
export function useInView(
1217
options: IntersectionOptions = {},
1318
): InViewHookResponse {
1419
const ref = React.useRef<Element>()
15-
const [state, setState] = React.useState<State>({
16-
inView: false,
17-
entry: undefined,
18-
})
20+
const [state, setState] = React.useState<State>(initialState)
1921

2022
const setRef = React.useCallback(
2123
node => {
2224
if (ref.current) {
2325
unobserve(ref.current)
26+
setState(initialState)
2427
}
2528
if (node) {
2629
observe(
@@ -43,7 +46,5 @@ export function useInView(
4346
[options.threshold, options.root, options.rootMargin, options.triggerOnce],
4447
)
4548

46-
React.useDebugValue(state.inView)
47-
4849
return [setRef, state.inView, state.entry]
4950
}

0 commit comments

Comments
 (0)