title: React hooks useEffect call API second time and first time calling API response also returning
body: <p>I'm fetching API with useEffect and API responding correct like </p>
  
  <pre><code>{response: {message: "This is a image link", status: "success"}, error: null}
  </code></pre>
  
  <p>Second time when I'm receiving next API call response and If there is a error then old response is not removing. It's showing like this</p>
  
  <pre><code>{response: {message: "This is a image link", status: "success"}, error: TypeError}
  </code></pre>
  
  <p>I worked <a href="https://scotch.io/tutorials/create-a-custom-usefetch-react-hook" rel="nofollow noreferrer">this</a> tutorial code for fetching API </p>
  
  <p>Check my exact code in <a href="https://codesandbox.io/s/blissful-taussig-lj01m" rel="nofollow noreferrer">codesandbox</a></p>
  
  <pre><code>import React, { useState } from "react";
  import ReactDOM from "react-dom";
  import "./styles.css";
  
  const useFetch = (url, options) =&gt; {
    console.log("useFetch");
    const [response, setResponse] = React.useState(null);
    const [error, setError] = React.useState(null);
  
    React.useEffect(() =&gt; {
      const FetchData = async () =&gt; {
        try {
          const res = await fetch(url, options);
          const json = await res.json();
          setResponse(json);
          // console.log("json - ", json);
        } catch (error) {
          // console.log("error - ", error);
          setError(error);
        }
      };
      FetchData();
    }, [url]);
    return { response, error };
  };
  
  function App() {
    const API_URL = `https://dog.ceo/api/breeds/image/random`;
    const [apiUrl, setApiUrl] = useState(API_URL);
    const res = useFetch(apiUrl, {});
    console.log("res - ", res);
    if (!res.response) {
      return &lt;div&gt;Loading...&lt;/div&gt;;
    }
  
    const apiCallAgain = () =&gt; {
      const apiUrl = `https://d.ceo/api/breeds/image/q`;
      setApiUrl(apiUrl);
    };
    const dogName = res.response.status;
    const imageUrl = res.response.message;
    return (
      &lt;div className="App"&gt;
        &lt;div&gt;
          &lt;button onClick={apiCallAgain}&gt;API Call&lt;/button&gt;
          &lt;h3&gt;{dogName}&lt;/h3&gt;
          &lt;div&gt;
            &lt;img src={imageUrl} alt="avatar" /&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
  
  const rootElement = document.getElementById("root");
  ReactDOM.render(&lt;App /&gt;, rootElement);
  
  </code></pre>
  
  <p>open console and check <code>res</code> object by default. Now click on <code>API Call</code> button and check <code>res</code> object again. When I'm using useState <code>null</code> in starting then why old state is showing?</p>