BiteSize 1: Detect Scrolling and Setting Conditional Renders

or how to set a Boolean when scrolling occurs in a certain area

Hugh Burgess
2 min readMar 23, 2023
source: Unsplash

Hello everyone! Here is the start of a new series I’ve been thinking of, where I jot down a little code which I found to be super useful in my week, and is hopefully not complex enough to understand.

Today I’ll show you an example of how to detect scrolling in the first 100 pixels, and conditionally render something as a result. This is a real working example which I used where I had a button I only wanted to be visible when I was at the very top of the page.

import { useEffect, useState } from 'react'

function MyComponent() {
const [scrolled, setScrolled] = useState(false)

useEffect(() => {
const handleScroll = () => {
const scrollY = window.scrollY
if (scrollY > 100) {
setScrolled(true)
} else {
setScrolled(false)
}
}

window.addEventListener('scroll', handleScroll)

return () => {
window.removeEventListener('scroll', handleScroll)
}
}, [])

return (
<div>
{scrolled ? (
<p>You have scrolled more than 100 pixels!</p>
) : (
<p>Keep scrolling...</p>
)}
</div>
)
}

In this code snippet, we use the `useEffect` hook to add a scroll listener to the window. Whenever the user scrolls, we check the `window.scrollY` value and update our `scrolled` state accordingly. We also clean up the listener when the component unmounts.

In your actual implementation, you might want to customize the threshold value (`100` in this case), or use a debounced version of `handleScroll()` to improve performance.

That’s it! Til next time :)

--

--