Skip to content

Commit b31487b

Browse files
committed
refactor: switch to useCallback for setting node ref
1 parent 828cfa9 commit b31487b

File tree

1 file changed

+22
-26
lines changed

1 file changed

+22
-26
lines changed

src/useInView.tsx

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -11,40 +11,36 @@ type State = {
1111
export function useInView(
1212
options: IntersectionOptions = {},
1313
): InViewHookResponse {
14-
const [ref, setRef] = React.useState<Element | null | undefined>(null)
14+
const ref = React.useRef<Element>()
1515
const [state, setState] = React.useState<State>({
1616
inView: false,
1717
entry: undefined,
1818
})
1919

20-
React.useEffect(
21-
() => {
22-
if (!ref) return
23-
observe(
24-
ref,
25-
(inView, intersection) => {
26-
setState({ inView, entry: intersection })
27-
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-
options,
34-
)
20+
const setRef = React.useCallback(
21+
node => {
22+
if (ref.current) {
23+
unobserve(ref.current)
24+
}
25+
if (node) {
26+
observe(
27+
node,
28+
(inView, intersection) => {
29+
setState({ inView, entry: intersection })
3530

36-
return () => {
37-
unobserve(ref)
31+
if (inView && options.triggerOnce) {
32+
// If it should only trigger once, unobserve the element after it's inView
33+
unobserve(node)
34+
}
35+
},
36+
options,
37+
)
3838
}
39+
40+
// Store a reference to the node
41+
ref.current = node
3942
},
40-
[
41-
// Only create a new Observer instance if the ref or any of the options have been changed.
42-
ref,
43-
options.threshold,
44-
options.root,
45-
options.rootMargin,
46-
options.triggerOnce,
47-
],
43+
[options.threshold, options.root, options.rootMargin, options.triggerOnce],
4844
)
4945

5046
React.useDebugValue(state.inView)

0 commit comments

Comments
 (0)