title: How to use setTimeout() along with React Hooks useEffect and setState?
body: <p>I want to wait for 10 seconds for my API call to fetch the category list array from backend and store in hook state. If nothing is fetched in 10 sec, I want to set error hook state to true.</p>
  
  <p>But the problem is even after the array is fetched initially, the error state is set to true and categoriesList array in state blanks out after 10 sec.</p>
  
  <pre><code>import React, { useState, useEffect } from "react";
  
  import { doGetAllCategories } from "../helper/adminapicall.js";
  
  const ViewCategories = () =&gt; {
    let [values, setValues] = useState({
      categoriesList: "",
      error: false,
    });
  
    let { categoriesList, error } = values;
  
    const preloadCategories = () =&gt; {
      doGetAllCategories()
        .then((data) =&gt; {
          if (data.error) {
            return console.log("from preload call data - ", data.error);
          }
          setValues({ ...values, categoriesList: data.categories });
        })
        .catch((err) =&gt; {
          console.log("from preload - ", err);
        });
    };
  
    useEffect(() =&gt; {
      preloadCategories();
  
      let timerFunc = setTimeout(() =&gt; {
        if (!categoriesList &amp;&amp; !error) {
          setValues({
            ...values,
            error: "Error fetching category list... try after some time !",
          });
        }
      }, 10000);
  
      return () =&gt; {
        clearTimeout(timerFunc);
      };
    }, []);
  
  
  
  //...further code
  </code></pre>