I’m trying to call an animation but simultaneously call an async function. Once that resolves it should stop the animation
console.log(context, "context value outside") //updating
const animate = useCallback(
async (index = 0) => {
console.log(context, "context value inside") //not updating
return setTimeout(() => {
// do animate
if (index === 3) {
animate(0)
} else {
animate(index + 1)
}
}, 800)
},
[context]
)
but when I call my trigger function that calls animate()
and getAsyncFunction()
it never updates the context value but I know the context value is updating because logging it in the main component body above renders a different value. why would it not update here? I even wrapped in useCallback to trigger it
2
Answers
Please note that while a context object is specified as dependency for useCallback, it must specify the value of the context, not the context object as such. Please see below two sample codes, and see the difference.
a. When the context value is in the dependency array, then useCallback has returned the latest function definition on each change of the value.
b. When the context as such is in the dependency array, then useCallback does not return the latest definition.
Case a
App.js
Test run
Browser console logs as below :
Case b
App.js
Test run
Browser console logs as below: