<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Hammad Afzal</title>
    <description>The latest articles on DEV Community by Hammad Afzal (@mhammad33).</description>
    <link>https://dev.to/mhammad33</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2014696%2F1e74d69d-8ce9-416c-a75d-a0f7bc9f6e31.jpg</url>
      <title>DEV Community: Hammad Afzal</title>
      <link>https://dev.to/mhammad33</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mhammad33"/>
    <language>en</language>
    <item>
      <title>Building Your Own Custom Hook in React: A Simple Guide to Fetching Data</title>
      <dc:creator>Hammad Afzal</dc:creator>
      <pubDate>Mon, 23 Sep 2024 11:36:14 +0000</pubDate>
      <link>https://dev.to/mhammad33/building-your-own-custom-hook-in-react-a-simple-guide-to-fetching-data-4d96</link>
      <guid>https://dev.to/mhammad33/building-your-own-custom-hook-in-react-a-simple-guide-to-fetching-data-4d96</guid>
      <description>&lt;h2&gt;
  
  
  1. Introduction
&lt;/h2&gt;

&lt;p&gt;When working with React, managing state and side effects — like fetching data — can get repetitive, especially if you have similar logic in multiple components. This is where &lt;strong&gt;custom hooks&lt;/strong&gt; come in handy. They allow you to bundle reusable logic into a single function, making your code cleaner and easier to manage.&lt;/p&gt;

&lt;p&gt;In this blog, we’ll create a custom hook called &lt;code&gt;useCountry&lt;/code&gt;that fetches information about countries from an API. We’ll break down each step to ensure you can easily follow along.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. What is a React Hook?
&lt;/h2&gt;

&lt;p&gt;Before we jump into custom hooks, let’s quickly review some built-in hooks in React:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useState:&lt;/strong&gt; Think of this as a container that holds information that can change over time, like user input in a form.&lt;br&gt;
&lt;strong&gt;useEffect:&lt;/strong&gt; This is like a timer that tells React to perform a certain action after something happens, such as fetching data from a server.&lt;/p&gt;
&lt;h3&gt;
  
  
  A Quick Example
&lt;/h3&gt;

&lt;p&gt;Imagine you’re building a simple form. You’d use &lt;code&gt;useState&lt;/code&gt;to keep track of the input values (like a shopping list) and &lt;code&gt;useEffect&lt;/code&gt;to trigger actions when those values change (like updating the list).&lt;/p&gt;

&lt;p&gt;These built-in hooks are the building blocks for creating custom hooks, which let you reuse logic across different components.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. Step-by-Step Guide to Building the Custom Hook
&lt;/h2&gt;
&lt;h3&gt;
  
  
  Step 1: Define the Purpose of Your Hook
&lt;/h3&gt;

&lt;p&gt;We’re going to create a custom hook called &lt;code&gt;useCountry&lt;/code&gt;, which will fetch country details based on the name you provide. It will handle loading states and any errors that may occur.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Challenge&lt;/strong&gt;: Think of another use case for a custom hook. What kind of data would you like to fetch?&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 2: Initial Setup
&lt;/h3&gt;

&lt;p&gt;We’ll use **Axios **to make our API calls. Axios simplifies the process of sending requests and gives better error messages compared to the Fetch API.&lt;/p&gt;

&lt;p&gt;Here’s a basic outline of our custom hook:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from 'react';
import axios from 'axios';

function useCountry(countryName) {
  const [data, setData] = useState(null); // Holds fetched country data
  const [loading, setLoading] = useState(true); // Tracks loading state
  const [error, setError] = useState(null); // Tracks errors

  useEffect(() =&amp;gt; {
    if (!countryName) return; // If countryName is empty, exit early

    const fetchCountry = async () =&amp;gt; {
      setLoading(true); // Start loading
      try {
        const response = await axios.get(`https://restcountries.com/v3.1/name/${countryName}`);
        setData(response.data[0]); // Set country data
      } catch (err) {
        setError(err.response ? err.response.data.message : err.message); // Handle errors
      } finally {
        setLoading(false); // End loading
      }
    };

    fetchCountry(); // Call the function to fetch data
  }, [countryName]); // Re-run if countryName changes

  return { data, loading, error }; // Return state
}

export default useCountry;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Key points:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Axios automatically converts JSON responses, so you don’t have to do it manually.&lt;/li&gt;
&lt;li&gt;It provides better error messages, making debugging easier.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Try It Yourself:&lt;/strong&gt; Copy the code into your editor and change the country name to see different results!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Step 3: Handle Edge Cases
&lt;/h3&gt;

&lt;p&gt;It’s essential to manage edge cases — like when the country name is invalid or empty. Here’s how we can enhance our hook:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
  if (!countryName) {
    setError('Country name is required'); // Set error if no input
    setLoading(false);
    return; // Exit if country name is empty
  }

  const fetchCountry = async () =&amp;gt; {
    setLoading(true);
    try {
      const response = await axios.get(`https://restcountries.com/v3.1/name/${countryName}`);
      setData(response.data[0]);
    } catch (err) {
      setError(err.response ? err.response.data.message : err.message);
    } finally {
      setLoading(false);
    }
  };

  fetchCountry();
}, [countryName]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Example Scenarios:
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Invalid Country Name:&lt;/strong&gt; If you input “Atlantis,” the API will return a 404 error, which we can catch and display.&lt;br&gt;
&lt;strong&gt;Empty Input:&lt;/strong&gt; If the input is empty, we show an error message indicating that a country name is required.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 4: Using the Custom Hook in a Component
&lt;/h3&gt;

&lt;p&gt;Now that we have our useCountry hook, let’s use it in a component to fetch and show country details.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import useCountry from './useCountry';

const CountryInfo = () =&amp;gt; {
  const [country, setCountry] = useState(''); // State for country input
  const { data, loading, error } = useCountry(country); // Use custom hook

  const handleInputChange = (e) =&amp;gt; {
    setCountry(e.target.value); // Update country state
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input
        type="text"
        value={country}
        onChange={handleInputChange}
        placeholder="Enter country name"
      /&amp;gt;
      {loading &amp;amp;&amp;amp; &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;} // Show loading message
      {error &amp;amp;&amp;amp; &amp;lt;p&amp;gt;Error: {error}&amp;lt;/p&amp;gt;} // Show error message
      {data &amp;amp;&amp;amp; (
        &amp;lt;div&amp;gt;
          &amp;lt;h2&amp;gt;{data.name.common}&amp;lt;/h2&amp;gt;
          &amp;lt;p&amp;gt;Population: {data.population}&amp;lt;/p&amp;gt;
          &amp;lt;p&amp;gt;Region: {data.region}&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
      )}
    &amp;lt;/div&amp;gt;
  );
};

export default CountryInfo;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  User Interaction
&lt;/h4&gt;

&lt;p&gt;When a user types “&lt;strong&gt;Pakistan&lt;/strong&gt;” into the input field, our component will fetch and display the country details.&lt;/p&gt;

&lt;p&gt;Try It Yourself: Create an input field using the &lt;code&gt;CountryInfo&lt;/code&gt;component. What happens when you enter different country names?&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Best Practices for Custom Hooks
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Naming Conventions:&lt;/strong&gt; Always start your custom hook with “use,” like &lt;code&gt;useCountry&lt;/code&gt;. This helps clarify that it follows React's hook rules.&lt;br&gt;
&lt;strong&gt;Reusability:&lt;/strong&gt; Make sure your hook is versatile enough to be used in multiple components. For example, a hook for form handling can work with different forms.&lt;br&gt;
&lt;strong&gt;Handling Side Effects:&lt;/strong&gt; Always use &lt;code&gt;useEffect&lt;/code&gt;for side effects (like API calls) within your hook. This keeps your components focused on their primary job.&lt;br&gt;
&lt;strong&gt;Example:&lt;/strong&gt; How could you modify &lt;code&gt;useCountry&lt;/code&gt;to include a search history? Share your ideas!&lt;/p&gt;

&lt;h2&gt;
  
  
  5. When Not to Use Custom Hooks
&lt;/h2&gt;

&lt;p&gt;Custom hooks are great, but they’re not always needed. Here are times when they might not be the best choice:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Single-Use Logic:&lt;/strong&gt; If the logic is specific to one component and won’t be reused, there’s no need to create a custom hook.&lt;br&gt;
&lt;strong&gt;Simple State Management:&lt;/strong&gt; If managing state is straightforward (like a toggle switch), making a custom hook could complicate things.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Reflection:&lt;/strong&gt; Think about recent projects. Have you created any logic that might benefit from being turned into a custom hook? Share your thoughts!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  6. Conclusion
&lt;/h2&gt;

&lt;p&gt;Custom hooks in React help you manage state and side effects while keeping your components clean and reusable. We’ve shown how to build a custom hook using &lt;strong&gt;Axios&lt;/strong&gt;to fetch country details, manage loading and error states, and handle edge cases.&lt;/p&gt;

&lt;p&gt;By using custom hooks, you can make your code more organized and maintainable. Start creating your own custom hooks for tasks like data fetching or form handling!&lt;/p&gt;

&lt;h3&gt;
  
  
  Final Challenge
&lt;/h3&gt;

&lt;p&gt;Try &lt;strong&gt;creating your own custom hook&lt;/strong&gt; for a different purpose, such as fetching weather data. Can you build it? If not, feel free to revisit this material for a deeper understanding.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>reactjsdevelopment</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Deploy Your Node.js TypeScript App on Vercel Quickly and Efficiently: A Step-by-Step Guide</title>
      <dc:creator>Hammad Afzal</dc:creator>
      <pubDate>Mon, 02 Sep 2024 10:09:39 +0000</pubDate>
      <link>https://dev.to/mhammad33/deploy-your-nodejs-typescript-app-on-vercel-quickly-and-efficiently-a-step-by-step-guide-43ag</link>
      <guid>https://dev.to/mhammad33/deploy-your-nodejs-typescript-app-on-vercel-quickly-and-efficiently-a-step-by-step-guide-43ag</guid>
      <description>&lt;p&gt;Deploying a Node.js app with TypeScript on Vercel can be quick and straightforward — if you set it up correctly. Vercel offers seamless deployment with powerful CI/CD capabilities, making it ideal for modern web applications. This guide will help you navigate the setup process, &lt;strong&gt;sidestep common configuration errors&lt;/strong&gt;, and ensure your deployment is successful.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before getting started, make sure you have the following:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vercel Free Account:&lt;/strong&gt; &lt;a href="https://vercel.com/" rel="noopener noreferrer"&gt;Sign up here&lt;/a&gt; to get started and deploy your apps effortlessly..&lt;br&gt;
&lt;strong&gt;Node.js &amp;amp; NPM:&lt;/strong&gt; &lt;a href="https://nodejs.org/en" rel="noopener noreferrer"&gt;Install Node.js&lt;/a&gt; if you haven’t already. This will also install npm, essential for running JavaScript packages..&lt;br&gt;
&lt;strong&gt;API Setup:&lt;/strong&gt; Have an existing API ready, or create a simple one.. Check out my &lt;a href="https://github.com/MHammad33/Notes-App/tree/Vercel-Deploy" rel="noopener noreferrer"&gt;reference repository&lt;/a&gt; for a quick setup guide that gets you up and running in minutes.&lt;/p&gt;
&lt;h2&gt;
  
  
  2. Setting Up Your Project
&lt;/h2&gt;

&lt;p&gt;Let’s start by setting up a basic Node.js project with TypeScript.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 1: Initialize Your Project
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 2: Install Key Packages
&lt;/h3&gt;

&lt;p&gt;Install the essential packages for TypeScript and Node.js development:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express typescript ts-node @types/node @types/express
ts-node-dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;express:&lt;/strong&gt; Minimalist web framework for Node.js, used to set up routing and middleware.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;typescript:&lt;/strong&gt; Superset of JavaScript that adds static typing, enhancing code quality and catching errors early.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;ts-node-dev:&lt;/strong&gt; Runs TypeScript files with hot-reloading, streamlining the development process.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Configure TypeScript (tsconfig.json)
&lt;/h2&gt;

&lt;p&gt;The tsconfig.json file controls how TypeScript compiles your code. Here’s a recommended configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES6",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      "*": [
        "node_modules/*",
        "src/types/*"
      ]
    }
  },
  "include": [
    "./src/**/*"
  ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Key Configurations Explained:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;"module":&lt;/strong&gt; &lt;code&gt;"commonjs"&lt;/code&gt;: Ensures compatibility with Node.js.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;"target":&lt;/strong&gt; &lt;code&gt;"ES6"&lt;/code&gt;: Compiles code to ES6 standards, allowing modern JavaScript features.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;"outDir":&lt;/strong&gt; &lt;code&gt;"dist"&lt;/code&gt;: Specifies the output folder for compiled files, crucial for Vercel deployments.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;"paths":&lt;/strong&gt; Helps alias directories, making imports cleaner and the codebase more maintainable.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4. Set Up Scripts in package.json
&lt;/h2&gt;

&lt;p&gt;Next, configure scripts in your package.json to manage development, build, and deployment workflows effectively:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
  "start": "npx nodemon src/index.ts",
  "dev": "npx nodemon src/index.ts",
  "build:ui": "@powershell Remove-Item -Recurse -Force dist &amp;amp;&amp;amp; cd ../frontend &amp;amp;&amp;amp; npm run build &amp;amp;&amp;amp; @powershell Copy-Item -Recurse dist ../backend",
  "lint": "eslint ."
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Scripts Overview:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;start: Runs the app in development mode with live reloading using nodemon.&lt;/li&gt;
&lt;li&gt;build:ui: Cleans the dist directory, builds the frontend, and copies static files to the backend. This is particularly useful for monorepo setups.&lt;/li&gt;
&lt;li&gt;lint: Uses ESLint to maintain code quality and consistency by identifying problematic patterns in JavaScript.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  5. Vercel Deployment Configuration
&lt;/h2&gt;

&lt;p&gt;Deploying to Vercel requires a &lt;code&gt;vercel.json&lt;/code&gt; file to define your build and route configurations. Here's a basic setup:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "version": 2,
  "builds": [
    {
      "src": "dist/index.js",
      "use": "@vercel/node",
      "config": { "includeFiles": ["dist/**"] }
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "dist/index.js"
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Configuration Highlights:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Builds:&lt;/strong&gt; Specifies the entry point (&lt;code&gt;dist/index.js&lt;/code&gt;) and includes necessary files.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Routes:&lt;/strong&gt; Directs all incoming requests to the main file and handles CORS, which is crucial for cross-origin requests.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6. Common Deployment Issues &amp;amp; Fixes
&lt;/h2&gt;

&lt;p&gt;Deployments often run into a few common issues. Here’s how to tackle them:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Build Failures:&lt;/strong&gt; Make sure your &lt;code&gt;dist&lt;/code&gt; folder is generated correctly. Double-check file paths in &lt;code&gt;vercel.json&lt;/code&gt; to ensure all required files are included.&lt;br&gt;
&lt;strong&gt;CORS Errors:&lt;/strong&gt; Modify CORS headers in &lt;code&gt;vercel.json&lt;/code&gt; to suit your API’s specific needs, ensuring smooth communication between the frontend and backend.&lt;br&gt;
&lt;strong&gt;Missing Dependencies:&lt;/strong&gt; Verify all dependencies in &lt;code&gt;package.json&lt;/code&gt; are installed correctly and up-to-date to prevent build breaks.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Conclusion
&lt;/h2&gt;

&lt;p&gt;Deploying a TypeScript-based Node.js app on Vercel can be smooth and efficient with the right configurations. Focus on setting up your &lt;code&gt;tsconfig.json&lt;/code&gt;, &lt;code&gt;package.json&lt;/code&gt;, and &lt;code&gt;vercel.json&lt;/code&gt; accurately to streamline the process. If you need a complete example or further tweaks, feel free to explore &lt;a href="https://github.com/MHammad33/Notes-App/tree/Vercel-Deploy" rel="noopener noreferrer"&gt;my complete codebase&lt;/a&gt; here for further reference and tweak the configurations as needed.&lt;/p&gt;

&lt;p&gt;Next Steps: Test these configurations locally before deploying to ensure everything works as expected. Follow me for more guides, and don’t hesitate to share your deployment experiences or ask questions!&lt;/p&gt;

&lt;p&gt;Happy coding and deploying on Vercel! 🍻&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>vercel</category>
      <category>node</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
