0

This blog post and the official docs show how to use useCallback to create a callback ref.

But neither one has an example of a case where useCallback has dependencies.

How should I set that up?

For example, if I do the following, it won't work, because the callback will be triggered without any arguments whenever myDependency changes.

const [myDependency, setMyDependency] = useState();

const myRef = useCallback(node => {
    doSomeMagic(node, myDependency);
}, [myDependency]);
nbrustein
  • 727
  • 5
  • 16

1 Answers1

0

I think the best way to do this is to split the logic out into a useCallback and a useEffect. useCallback is used to keep track of the node. useEffect is used to trigger whenever the node changes OR myDependency changes.

const [node, setNode] = useState();
const [myDependency, setMyDependency] = useState();

const myRef = useCallback(node => {
    setNode(node);
}, []);

useEffect(() => {
    doSomeMagic(node, myDependency);
}, [node, myDependency]);

nbrustein
  • 727
  • 5
  • 16