... so if you had a button that read the value of 'count' it would always return zero.
The reason why is that useCallback caches the value of 'count' and you get the stale version each time.
You have to add 'count' in a dependency on useCallback before the last paren.
There are about 2-4 of these that I need to write down and document but this one has bitten me most often.
Also, React, in general, can't work well with Typescript to catch compiler issues.
For example, Typescript can catch compile errors when you're building a component and you're missing a variable name.
With React context it's more of a global and if you are using a component which doesn't have context setup you will/could get a runtime error or at least a bad bug.
It would be MUCH better, IMO, to have a React-like language that was Typescript aware from the beginning.
Is there any doc about how this caching is implemented ? I still don't understand why we need to feed this dependency array to have an up to date version of the count variable.
The problem is that there are subtle bugs that just aren't obvious at first.
Here's a simple one.
let count: number = 0;
const myCallback = React.useCallback(() => { ++count; return count; }, []);
... so if you had a button that read the value of 'count' it would always return zero.
The reason why is that useCallback caches the value of 'count' and you get the stale version each time.
You have to add 'count' in a dependency on useCallback before the last paren.
There are about 2-4 of these that I need to write down and document but this one has bitten me most often.
Also, React, in general, can't work well with Typescript to catch compiler issues.
For example, Typescript can catch compile errors when you're building a component and you're missing a variable name.
With React context it's more of a global and if you are using a component which doesn't have context setup you will/could get a runtime error or at least a bad bug.
It would be MUCH better, IMO, to have a React-like language that was Typescript aware from the beginning.