Skip to content

Commit daf56df

Browse files
committed
fix: broken hook updates
Hooks were comparing against the previous state.inView, without having access to that value. This resulted in hooks never triggering when outside the viewport.
1 parent fc9aeee commit daf56df

File tree

3 files changed

+297
-296
lines changed

3 files changed

+297
-296
lines changed

package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@
128128
"@typescript-eslint/parser": "^1.4.2",
129129
"babel-core": "^7.0.0-bridge.0",
130130
"babel-eslint": "10.0.1",
131-
"babel-jest": "^24.4.0",
131+
"babel-jest": "^24.5.0",
132132
"babel-loader": "^8.0.5",
133133
"concurrently": "4.1.0",
134134
"coveralls": "^3.0.3",
@@ -140,8 +140,8 @@
140140
"eslint-plugin-react": "7.x",
141141
"husky": "^1.3.1",
142142
"intersection-observer": "^0.5.1",
143-
"jest": "^24.4.0",
144-
"jest-dom": "^3.1.1",
143+
"jest": "^24.5.0",
144+
"jest-dom": "^3.1.3",
145145
"lint-staged": "^8.1.5",
146146
"npm-run-all": "^4.1.5",
147147
"prettier": "^1.16.2",

src/useInView.tsx

Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -14,39 +14,32 @@ export function useInView(options: IntersectionOptions = {}): HookResponse {
1414
entry: undefined,
1515
})
1616

17-
React.useEffect(
18-
() => {
19-
if (!ref) return
20-
observe(
21-
ref,
22-
(inView, intersection) => {
23-
// Only trigger a state update if inView has changed.
24-
// This prevents an unnecessary extra state update during mount, when the element stats outside the viewport
25-
if (inView !== state.inView || inView) {
26-
setState({ inView, entry: intersection })
17+
React.useEffect(() => {
18+
if (!ref) return
19+
observe(
20+
ref,
21+
(inView, intersection) => {
22+
setState({ inView, entry: intersection })
2723

28-
if (inView && options.triggerOnce) {
29-
// If it should only trigger once, unobserve the element after it's inView
30-
unobserve(ref)
31-
}
32-
}
33-
},
34-
options,
35-
)
24+
if (inView && options.triggerOnce) {
25+
// If it should only trigger once, unobserve the element after it's inView
26+
unobserve(ref)
27+
}
28+
},
29+
options,
30+
)
3631

37-
return () => {
38-
unobserve(ref)
39-
}
40-
},
41-
[
42-
// Only create a new Observer instance if the ref or any of the options have been changed.
43-
ref,
44-
options.threshold,
45-
options.root,
46-
options.rootMargin,
47-
options.triggerOnce,
48-
],
49-
)
32+
return () => {
33+
unobserve(ref)
34+
}
35+
}, [
36+
// Only create a new Observer instance if the ref or any of the options have been changed.
37+
ref,
38+
options.threshold,
39+
options.root,
40+
options.rootMargin,
41+
options.triggerOnce,
42+
])
5043

5144
React.useDebugValue(state.inView)
5245

0 commit comments

Comments
 (0)