Passing variable that changes over time to a Listener

Viewed 47

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.

1 Answers

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 */};
}, [])
Related