简体   繁体   中英

How to correctly pass parameters to useCallback() hook?

Console warning “ React Hook useEffect has a missing dependency: 'animate'. Either include it or remove the dependency array. "

If the animate function is set in brackets

return () => {cancelAnimationFrame (refAnimation.current)}}, [animate])

It gives another warning " The 'animate' function makes the dependencies of useEffect Hook change on every render. To fix this, wrap the definition of 'animate' in its own useCallback () Hook. "

I try to wrap the function in the useCacllback hook , but apparently I'm doing it wrong and I get an error:

React Hook useCallback does nothing when called with only one argument. Did you forget to pass an array of dependencies?

const animate = useCallback(() => {
   refAnimation.current = requestAnimationFrame(() =>
   animate(cur, rez, speed)
);
   cur = cur + speed;
   ref.current.style.marginLeft = cur.toFixed(2) + "px";

   if (Math.round(cur) === rez) {
   cancelAnimationFrame(refAnimation.current);
}

});

I can't figure out how to correctly pass parameters to the useCallback() to pass them further to animate() ?

Full version of the code https://codesandbox.io/s/old-frog-6nwfq?file=/src/scroll.js

 let ref = useRef(); let refAnimation = useRef(); ... const animate = (cur, rez, speed) => { refAnimation.current = requestAnimationFrame(() => animate(cur, rez, speed) ); cur = cur + speed; ref.current.style.marginLeft = cur.toFixed(2) + "px"; if (Math.round(cur) === rez) { cancelAnimationFrame(refAnimation.current); } }; useEffect(() => { if (ref.current === true) { refAnimation.current = requestAnimationFrame(() => animate(0, 0, 0)); } return () => { cancelAnimationFrame(refAnimation.current); }; }, [animate]);

When you are using useCallback you are memoizing that callback based on some parameters. Here you haven't specified any parameter. If that's not the case and it should be created just once (and not to be re-created based on a change in some other values/states), you have to pass an empty array as the second argument to useCallback . It causes this callback to be created just once, when component mounts.
Take a look at the documentation: https://reactjs.org/docs/hooks-reference.html#usecallback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM