Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
The right approach to add window event listeners in the functional component

It's pretty easy to add event listeners in the functional component:

const Component = () => {
   const handleScroll = () => {
      // body
   }

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

But it's okay if handleScroll doesn't change. Sometimes it changes a lot (due to props change, state changes and etc.) and it should be added to useEffect dependencies list:

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

Is it a normal practice to add and remove window listeners on almost each render of the component? Maybe, it's the situation when it's better to use class components that have an internal state?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should always pass handleScroll in the useEffects deps array.

Then, ways to limit re-rendering include wrapping handleScroll inside a useCallback and using refs.

Based on your limited example, not knowing for sure, but the ref approach in the useEventCallback example from the react docs might be helpful for your situation.

import { useEventCallback } from './myHooks'

function Component() {
  const [myChangingState, changeIt] = useState()

  const handleScroll = useEventCallback(() => {
    // body uses `myChangingState`
  }, [myChangingState]
)

which will keep it from updating on every render.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!