const MyComponent = () => {
const history = useHistory();
let [val, setVal] = useState(0);
useEffect(() => {
trackPageView();
history.listen(trackPageView);
}, []);
function trackPageView() {
console.log('hello: ' + val);
setVal(val + 1);
}
}
useEffect runs once and registers trackPageView with history.listen. As the history changes, trackPageView is called as expected but val always has the same start value of '0'. (The above code is based on the code in this article.)
In contrast, this code does a similar thing...
var a = 1;
function g(f) {
return () => f();
}
let func = g(() => console.log('a: ' + a));
func();
a = 2;
func();
...but a's changing value is reflected in the output. https://jsfiddle.net/s3e250da/
So, what accounts for the difference in behaviour?