Skip to content

Commit

Permalink
refactor: get rid of unobserve ref
Browse files Browse the repository at this point in the history
The flow is now contained in the useEffect
  • Loading branch information
thebuilder committed Jul 22, 2022
1 parent c84989e commit b6cecf6
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/useInView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ export function useInView({
onChange,
}: IntersectionOptions = {}): InViewHookResponse {
const [ref, setRef] = React.useState<Element | null>(null);
const unobserve = React.useRef<Function>();
const callback = React.useRef<IntersectionOptions['onChange']>();
const [state, setState] = React.useState<State>({
inView: !!initialInView,
Expand All @@ -62,7 +61,7 @@ export function useInView({
// Ensure we have node ref, and that we shouldn't skip observing
if (skip || !ref) return;

unobserve.current = observe(
let unobserve: (() => void) | undefined = observe(
ref,
(inView, entry) => {
setState({
Expand All @@ -71,10 +70,10 @@ export function useInView({
});
if (callback.current) callback.current(inView, entry);

if (entry.isIntersecting && triggerOnce && unobserve.current) {
if (entry.isIntersecting && triggerOnce && unobserve) {
// If it should only trigger once, unobserve the element after it's inView
unobserve.current();
unobserve.current = undefined;
unobserve();
unobserve = undefined;
}
},
{
Expand All @@ -90,9 +89,8 @@ export function useInView({
);

return () => {
if (unobserve.current) {
unobserve.current();
unobserve.current = undefined;
if (unobserve) {
unobserve();
}
};
},
Expand Down

0 comments on commit b6cecf6

Please sign in to comment.