I am trying to wrap my head around the React Hooks API. Specifically, I'm trying to construct the classic use case that once was the following:
componentDidUpdate(prevProps) {
if (prevProps.foo !== this.props.foo) {
// Animate DOM elements here...
this.animateSomething(this.ref, this.props.onAnimationComplete);
}
}
Now, I tried to build the same with a functional component and useEffect, but can't figure out how to do it. This is what I tried:
useEffect(() => {
animateSomething(ref, props.onAnimationComplete);
}, [props.foo]);
This way, the effect is only called when props.foo changes. And that does work – BUT! It appears to be an anti-pattern since the eslint-plugin-react-hooks rule warns about this. All dependencies that are used inside the effect should be declared in the dependencies array. So that means I would have to do the following:
useEffect(() => {
animateSomething(ref, props.onAnimationComplete);
}, [props.foo, ref, props.onAnimationComplete]);
That does not lead to the linting error BUT it totally defeats the purpose of only calling the effect when props.foo changes. I DON'T want it to be called when the other props or the ref change.
Now, I read something about using useCallback to wrap this. I tried it but didn't get any further.
props.onAnimationCompletechanges. Furthermore already runninganimateSomethingstill will use an old callback.