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

147
Visualizações
Passing variable that changes over time to a Listener

Problem: A listener uses the old value of a variable in a callback.

I'm trying to find a proper way to pass a variable to a callback. The callback should use a relevant value of the variable.

const [title, setTitle] = useState('');

useEffect(() => {
    notificationListener.current = Notifications.addNotificationReceivedListener(() => {
      foo(title);
    });

    return () => {/* Removing Listener */};
  }, [])

title mutates over time, and foo() should receive a relevant title value.

Solutions that I came up with so far:

  1. Keep value in useRef() instead of useState()
  2. Destroy and re-create listener on change title

But non of them looks like optimal approach. Please help.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Instead of creating anonymous function, you can create a function for listener and wrap it in useCallback

const callbackFunc = useCallback(()=>{
    foo(title)
},[title])

now your useEffect will be

useEffect(() => {
    notificationListener.current = Notifications.addNotificationReceivedListener(callbackFunc);

    return () => {/* Removing Listener */};
}, [])
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