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:
- Keep value in useRef() instead of useState()
- Destroy and re-create listener on change
title
But non of them looks like optimal approach. Please help.