I'm writing my first hook and I also use redux. I'm listening to orientation sensor data from the mobile device in React native and when it updates I filter it to see if the new value is different than the old value before I send it over to redux state to be stored.
I'm noticing in the filterData method the data is always null. But if I console log the storedVal in the render I see it's always being updated and it's updated in the Redux store as well.
But for some reason filterData only has access to the initial value and doesn't get the updated values. Any idea how to fix this?
const storedVal = useSelector(selectors.selectStoredVal);
const filterData = useCallback(
() => {
console.log(storedVal);
},
[storedVal]
);
useEffect(
() => {
orientation.pipe(filter(filterData)).subscribe((data) => {
console.log('Data filtered correctly, new data received here');
}
}
),
[];
}
An empty dependency array for useEffect means that the callback function within it will only run once (on component mount).
useCallback is creating a function that is being passed into the filter function. Because storedVal is a dependency for filteredData, went storedVal changes and filteredData is updated to a new function, your useEffect still has a reference to it's old value.
Try adding [filteredData] to your dependency array for the useEffect.