Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda