The useInView hook
Unlock this video and the rest of this course by joining Frontend.FYI PRO .
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.
const Component = () => { const elementRef = useRef(null); const isInView = useInView(elementRef);
return <div ref={elementRef} />;};
Unlock the full lesson with PRO
Want to read the full lesson? Join Frontend.FYI PRO.
PRO is a one time purchase of €249 that gives you lifetime access to this course, any courses released in the future, and so much more!