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:
titleBut non of them looks like optimal approach. Please help.
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 */};
}, [])