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

146
Views
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 answers
Answer question

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 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!