Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
useInView
import * as React from 'react'
import { observe, unobserve } from './intersection'
import { HookResponse, IntersectionOptions } from './typings/types'
type State = {
inView: boolean
entry?: IntersectionObserverEntry
}
export function useInView(options: IntersectionOptions = {}): HookResponse {
const [ref, setRef] = React.useState<Element | null | undefined>(null)
const [state, setState] = React.useState<State>({
inView: false,
entry: undefined,
})
React.useEffect(() => {
if (ref) {
observe(
ref,
(inView, intersection) => {
setState({ inView, entry: intersection })
},
options,
)
}
return () => {
if (ref) unobserve(ref)
}
}, [
// Only create a new Observer instance if the ref or any of the options have been changed.
ref,
options.threshold,
options.root,
options.rootMargin,
])
return [setRef, state.inView, state.entry]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.