score:1

Accepted answer

the reason for using usecallback is to keep the same reference to a function between renders when needed.

usecallback is supposed to accept callback function as an argument, as the name suggests. since usecallback(fn) is a shortcut for usememo(() => fn), it technically can be (mis)used with any argument:

const getfetchurl = usecallback('https://hn.algolia.com/api/v1/search?query=' + query, [query]);

there are no benefits from doing this because usememo and usecallback are intended for lazy evaluation, while this results in eager evaluation.

the example with getfetchurl callback isn't very illustrative because memoization doesn't provide any improvements, it could be simplified to:

function searchresults() {
  const [query, setquery] = usestate('react');

  const fetchurl = 'https://hn.algolia.com/api/v1/search?query=' + query;

  useeffect(() => {
    // ... fetch data and do something ...
  }, [fetchurl]);
}

as for greeting example, usecallback is redundant. if the calculation is really expensive and needs to be lazily evaluated (in this example it isn't), this is what usememo is for:

function greeting({ name }) {
  const result = usememo(() => {
    return `hello ${name}`;
  }, [name]);

  return <p>{result}</p>;
}

Related Query

More Query from same tag