Skip to content

Commit b6cecf6

Browse files
committed
refactor: get rid of unobserve ref
The flow is now contained in the useEffect
1 parent c84989e commit b6cecf6

1 file changed

Lines changed: 6 additions & 8 deletions

File tree

src/useInView.tsx

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ export function useInView({
4646
onChange,
4747
}: IntersectionOptions = {}): InViewHookResponse {
4848
const [ref, setRef] = React.useState<Element | null>(null);
49-
const unobserve = React.useRef<Function>();
5049
const callback = React.useRef<IntersectionOptions['onChange']>();
5150
const [state, setState] = React.useState<State>({
5251
inView: !!initialInView,
@@ -62,7 +61,7 @@ export function useInView({
6261
// Ensure we have node ref, and that we shouldn't skip observing
6362
if (skip || !ref) return;
6463

65-
unobserve.current = observe(
64+
let unobserve: (() => void) | undefined = observe(
6665
ref,
6766
(inView, entry) => {
6867
setState({
@@ -71,10 +70,10 @@ export function useInView({
7170
});
7271
if (callback.current) callback.current(inView, entry);
7372

74-
if (entry.isIntersecting && triggerOnce && unobserve.current) {
73+
if (entry.isIntersecting && triggerOnce && unobserve) {
7574
// If it should only trigger once, unobserve the element after it's inView
76-
unobserve.current();
77-
unobserve.current = undefined;
75+
unobserve();
76+
unobserve = undefined;
7877
}
7978
},
8079
{
@@ -90,9 +89,8 @@ export function useInView({
9089
);
9190

9291
return () => {
93-
if (unobserve.current) {
94-
unobserve.current();
95-
unobserve.current = undefined;
92+
if (unobserve) {
93+
unobserve();
9694
}
9795
};
9896
},

0 commit comments

Comments
 (0)