<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Deepanshu Goel Blogs]]></title><description><![CDATA[🌟 Passionate UI/UX Designer &amp; Full-Stack Developer at MagesStudio. Embracing MERN stack. Fuelled by open-source, creating extraordinary digital experiences! 🚀]]></description><link>https://blogs.deepanshuweb.in</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1686905788300/A2uetId5a.jpeg</url><title>Deepanshu Goel Blogs</title><link>https://blogs.deepanshuweb.in</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 18 May 2026 00:51:36 GMT</lastBuildDate><atom:link href="https://blogs.deepanshuweb.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Supercharging Data Fetching in React with Custom Hooks and React-Query]]></title><description><![CDATA[Section 1: Setting up React Query
React Query is a powerful library that simplifies data fetching and state management in React applications. It provides an elegant way to handle asynchronous operations and cache data for improved performance. Let's ...]]></description><link>https://blogs.deepanshuweb.in/supercharging-data-fetching-in-react-with-custom-hooks-and-react-query</link><guid isPermaLink="true">https://blogs.deepanshuweb.in/supercharging-data-fetching-in-react-with-custom-hooks-and-react-query</guid><category><![CDATA[React]]></category><category><![CDATA[react-query]]></category><category><![CDATA[custom-hooks]]></category><category><![CDATA[axios]]></category><category><![CDATA[data fetching]]></category><dc:creator><![CDATA[Deepanshu Goel]]></dc:creator><pubDate>Fri, 16 Jun 2023 08:37:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686904127045/c39c681f-1d09-4014-8188-e4d561107457.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-section-1-setting-up-react-query"><strong>Section 1: Setting up React Query</strong></h2>
<p>React Query is a powerful library that simplifies data fetching and state management in React applications. It provides an elegant way to handle asynchronous operations and cache data for improved performance. Let's get started by setting up React Query in our project.</p>
<p>To install React Query, you can use the following command:</p>
<pre><code class="lang-powershell">npm install @tanstack/react<span class="hljs-literal">-query</span>
</code></pre>
<p>Once installed, you can import the necessary dependencies:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">"@tanstack/react-query"</span>;
<span class="hljs-keyword">import</span> Cookies <span class="hljs-keyword">from</span> <span class="hljs-string">"js-cookie"</span>;
</code></pre>
<p>The <code>useQuery</code> hook is provided by React Query and allows us to fetch data from an API. We'll also be using the <code>Cookies</code> library to handle authentication tokens.</p>
<p>Now, let's take a look at the <code>fetchApi</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchApi = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> request({
    <span class="hljs-attr">url</span>: <span class="hljs-string">"/your-end-point"</span>,
    <span class="hljs-attr">method</span>: <span class="hljs-string">"GET"</span>,
  });
  <span class="hljs-keyword">return</span> response?.data?.data;
};
</code></pre>
<h2 id="heading-section-2-creating-the-custom-hook"><strong>Section 2: Creating the Custom Hook</strong></h2>
<p>Custom hooks are a powerful concept in React that allows us to encapsulate and reuse logic across multiple components. Let's create a custom hook called <code>useUsers</code> that leverage React Query to fetch user data.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> GET_API_NAME = <span class="hljs-string">'your-api-name'</span>;

<span class="hljs-keyword">const</span> useApiQuery = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> token = Cookies.get(<span class="hljs-string">"token"</span>);
  <span class="hljs-keyword">const</span> { isLoading, isError, data, error, refetch } = useQuery(
    [GET_API_NAME],
    fetchApi, {
      <span class="hljs-attr">enabled</span>: !!token,
      <span class="hljs-attr">onError</span>: <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.error(error);
      },
    }
  );
  <span class="hljs-keyword">return</span> { isLoading, isError, data, error, refetch };
};
<span class="hljs-keyword">export</span> { useApiQuery };
</code></pre>
<p>The <code>useApiQuery</code> hook uses the <code>useQuery</code> hook from React Query to handle the data fetching. It takes an array of dependencies, in this case <code>[GET_API_NAME]</code>, to identify the query. Whenever the dependencies change, React Query will automatically re-fetch the data. The <code>fetchApi</code> function we defined earlier is passed as the second argument.</p>
<p>The <code>enabled</code> option is set to <code>!!token</code> to control whether the query should be enabled based on the presence of the authentication token. If there is no token available, the query will not be executed.</p>
<p>The <code>onError</code> option allows us to handle any errors that occur during the query. In this case, we simply log the error to the console, but you can customize the error handling as per your requirements.</p>
<p>The hook returns an object containing various values: <code>isLoading</code> indicates whether the data is currently being fetched, <code>isError</code> indicates if an error occurred, <code>data</code> contains the fetched data, <code>error</code> holds the error object if any, and <code>refetch</code> is a function to manually trigger a data re-fetch.</p>
<h2 id="heading-section-3-setting-up-axios-and-authorization"><strong>Section 3: Setting up Axios and Authorization</strong></h2>
<p>To make API requests with authentication, we'll use Axios, a popular JavaScript library. Axios provides an easy-to-use API for sending HTTP requests and handling responses. Additionally, we'll configure Axios to include the authorization token in the request headers. Let's set it up.</p>
<p>First, install Axios and import the necessary dependencies:</p>
<pre><code class="lang-javascript">jsxCopy codeimport axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;
<span class="hljs-keyword">import</span> Cookies <span class="hljs-keyword">from</span> <span class="hljs-string">"js-cookie"</span>;
<span class="hljs-keyword">import</span> { getApiURL } <span class="hljs-keyword">from</span> <span class="hljs-string">"./baseURL"</span>;
</code></pre>
<p>Next, create an instance of Axios using the <code>axios.create</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> client = axios.create({
  <span class="hljs-attr">baseURL</span>: getApiURL(),
});
</code></pre>
<p>The <code>baseURL</code> is set using the <code>getApiURL</code> function, which should return the URL of your API.</p>
<p>Now, let's define a function called <code>setAuthorizationHeader</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> setAuthorizationHeader = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> token = Cookies.get(<span class="hljs-string">"token"</span>);
  <span class="hljs-keyword">if</span> (token) {
    client.defaults.headers.common[<span class="hljs-string">"Authorization"</span>] = <span class="hljs-string">`Bearer <span class="hljs-subst">${token}</span>`</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">delete</span> client.defaults.headers.common[<span class="hljs-string">"Authorization"</span>];
  }
};
</code></pre>
<p>The <code>setAuthorizationHeader</code> function retrieves the authentication token from cookies using <code>Cookies.get</code>. If a token is available, it sets the <code>Authorization</code> header in the Axios client to include the token. If there is no token, the <code>Authorization</code> header is deleted.</p>
<p>To initialize the authorization header, call <code>setAuthorizationHeader</code>:</p>
<pre><code class="lang-javascript">codesetAuthorizationHeader();
</code></pre>
<p>Additionally, we can add an interceptor to update the authorization header before each request:</p>
<pre><code class="lang-javascript">client.interceptors.request.use(<span class="hljs-function">(<span class="hljs-params">config</span>) =&gt;</span> {
  setAuthorizationHeader();
  <span class="hljs-keyword">return</span> config;
});
</code></pre>
<p>The interceptor calls <code>setAuthorizationHeader</code> to ensure that the latest token is included in the request headers.</p>
<p>Finally, we can define a <code>request</code> function to handle sending requests:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> request = <span class="hljs-function">(<span class="hljs-params">{ ...options }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> onSuccess = <span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> response;
  };
  <span class="hljs-keyword">const</span> onError = <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> error;
  };
  <span class="hljs-keyword">return</span> client(options).then(onSuccess).catch(onError);
};
</code></pre>
<p>The <code>request</code> function takes an options object and sends the request using the Axios client. It returns a promise that resolves with the response data on success or rejects with an error on failure.</p>
<h2 id="heading-section-4-usage"><strong>Section 4: Usage</strong></h2>
<p>Now that we have our custom hook <code>useUsers</code> set up, let's see how we can use it in a React component. We'll show an example of accessing the <code>data</code>, <code>isLoading</code>, and <code>refetch</code> properties returned by the <code>useApiQuery</code> hook.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { data, isLoading, refetch } = useApiQuery();
</code></pre>
<p>If the data is available, we can map over the <code>data</code> array and render a list item for each item in the data if it's an array.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this blog post, we learned how to build a custom hook using React Query for data fetching and Axios for handling API requests and authentication. By combining these powerful libraries, we can create efficient and reusable code for managing API calls in our React applications.</p>
<p>Feel free to customize and expand upon the code snippets provided to fit your specific use case.</p>
<p>If you found this blog post helpful, feel free to follow me on Twitter <a target="_blank" href="https://twitter.com/thedeepanshuweb"><strong>@</strong></a><a target="_blank" href="https://twitter.com/thedeepanshuweb"><strong>thedeepanshuweb</strong></a>, connect with me on LinkedIn <a target="_blank" href="https://www.linkedin.com/in/deepanshuweb/"><strong>Deepanshu Goel</strong></a></p>
]]></content:encoded></item></channel></rss>