The useInView hook
My first go to for scroll animations is the whileInView
prop discussed on the previous lesson. However, there are cases where you would like to have a variable in JavaScript too.
You might want to trigger specific events, play a sound, or run other JavaScript logic based on the inview state of an element. For this, there is a hook called useInView
.
Basic implementation
The useInView
hook is a function that accepts a ref to an HTML element. It will then track if that element is in view or not and return a boolean for you with that state.
As you can see in the example below, the hook does not return its own ref
, but rather expects you to pass one.
1const Component = () => {2 const elementRef = useRef(null);3 const isInView = useInView(elementRef);4
5 return (6 <div ref={elementRef} />7 );8}
Unlock the full lesson with PRO
Want to read the full lesson? Join Frontend.FYI PRO.
PRO is a one time purchase of €149 that gives you lifetime access to this course, any courses released in the future, and so much more!