Skip to content
Advertisement

Invoking function expression

I’m following a React-hooks tutorial and I don’t understand why does the function expression, timerId in the top useEffect is being invoked automatically, but the function expression, search, in the bottom useEffect requires it to be called search() in order to invoke it?

 useEffect(() => {
    const timerId = setTimeout(() => {
      setDebouncedTerm(term);
    }, 1500);
 
    return () => {
      clearTimeout(timerId);
    };
  }, [term]);
 
  useEffect (() => {
    const search = async() => {
      const { data } = await axios.get('https://en.wikipedia.org/w/api.php', {
        params: {
          action: 'query', 
          list: 'search',
          origin: '*',
          format: 'json', 
          srsearch: debouncedTerm
        }
      });
      setResults(data.query.search);
    };
    search();
  }, [debouncedTerm]);

Advertisement

Answer

It is assigning a function to search variable which needs to be invoked manually.

However in the body of other useEffect it is invoking the setTimeout function and assigning the return value of setTimeout function to timerId variable. Return value of setTimeout function is a positive integer which is the unique identifier of the timeout.

So the value of timerId is not a function to begin with. It’s the id of the timeout.

Only function that is being invoked in the body of top useEffect is the setTimeout function.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement