<?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>Forem: Shashwat Nautiyal</title>
    <description>The latest articles on Forem by Shashwat Nautiyal (@shashwatnautiyal).</description>
    <link>https://forem.com/shashwatnautiyal</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%2F999756%2F13f963fb-4dc4-49b3-a669-f29d47d97aa5.jpeg</url>
      <title>Forem: Shashwat Nautiyal</title>
      <link>https://forem.com/shashwatnautiyal</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/shashwatnautiyal"/>
    <language>en</language>
    <item>
      <title>Master Typescript using Infer and Conditional types</title>
      <dc:creator>Shashwat Nautiyal</dc:creator>
      <pubDate>Sun, 01 Jan 2023 10:11:06 +0000</pubDate>
      <link>https://forem.com/shashwatnautiyal/master-typescript-using-infer-and-conditional-types-48gd</link>
      <guid>https://forem.com/shashwatnautiyal/master-typescript-using-infer-and-conditional-types-48gd</guid>
      <description>&lt;p&gt;&lt;em&gt;Become an expert in typescript using Infer and Conditional Types&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What are infer and conditional types in TypeScript?
&lt;/h2&gt;

&lt;p&gt;Conditional types in typescript can help when you want to select the type of different kinds conditionally. Infer keyword makes dependent type more flexible. It allows users to infer some sort as a whole or a part of that type which is very powerful in some cases.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use infer and conditional types?
&lt;/h2&gt;

&lt;p&gt;The conditional type uses generics to pass the parameter constrained by a condition. The tertiary operator is used to select the type in the typescript if a condition is satisfied or not.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--h6QmXKMd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7r6m8sbhdwedgm04cifn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--h6QmXKMd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7r6m8sbhdwedgm04cifn.png" alt="Typescript Conditional Type" width="880" height="338"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Let us understand conditional types by an example 🧑🏻‍💻
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type User = {
    name: string,
    email: string,
    followers: number,
    following: number,
    posts: number
}

type Admin = {
    name: string,
    email: string,
    isVarified: boolean,
    hasDbAccess: boolean,
}

type Profile&amp;lt;T extends "USER" | "ADMIN"&amp;gt; = {
    createdAt: Date,
    id: string
    type: T extends "USER" ? "user" : "admin",
    data: T extends "USER" ? User : Admin 
}

type UserProfile = Profile&amp;lt;"USER"&amp;gt;
type AdminProfile = Profile&amp;lt;"ADMIN"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we have created two types &lt;code&gt;UserProfile&lt;/code&gt; and &lt;code&gt;AdminProfile&lt;/code&gt; that is extracted from &lt;code&gt;ProfileResponse&amp;lt;"USER" | "ADMIN"&amp;gt;&lt;/code&gt;. Typescript automatically determines the param passed in the arrow parameter and adds property accordingly. Conditional types help to reduce the number of lines in your classes and reduce redundancy in your code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Now let's checkout infer by an example ✍🏻
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type InferPromise&amp;lt;T&amp;gt; = T extends Promise&amp;lt;infer P&amp;gt;
  ? P
  : T extends (...args: any[]) =&amp;gt; Promise&amp;lt;infer P&amp;gt;
  ? P
  : never;

type GetFullName = InferPromise&amp;lt;Promise&amp;lt;{firstName: "groww", lastName: "tech"}&amp;gt;&amp;gt;

const getName = async () =&amp;gt; {
    return Promise.resolve({
        name: "groww"
    })
}

type GetName = InferPromise&amp;lt;typeof getName&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we have created a InferPromise type that can infer the promise from the function or directly from the Promise class. The above example looks a little complex, but you do not have to worry. We will see another example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type GetParamsAndReturn&amp;lt;T&amp;gt; = T extends (...args: infer P) =&amp;gt; infer R
  ? { params: P; returnType: R }
  : never;

const getUser = (firstName: string, lastName: string, email: string, phone: string) =&amp;gt; {

    return {
        name: firstName + lastName,
        email,
        phone,
        type: "user"
    }
}

type UserType = GetParamsAndReturn&amp;lt;typeof getUser&amp;gt;
type UserParams = UserType["params"];
type UserReturnType = UserType["returnType"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here &lt;code&gt;GetParamsAndReturn&amp;lt;T&amp;gt;&lt;/code&gt; can take any function and return the function parameters and return type. We can use this type to get any function's parameter and the return type.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we saw two of the advanced types in typescript. We also learned how we could use infer and conditional types in code. So, the next time you see the infer and conditional types, you will understand them properly.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>Understanding Generics in Typescript</title>
      <dc:creator>Shashwat Nautiyal</dc:creator>
      <pubDate>Sun, 01 Jan 2023 08:57:27 +0000</pubDate>
      <link>https://forem.com/shashwatnautiyal/understanding-generics-in-typescript-1p7l</link>
      <guid>https://forem.com/shashwatnautiyal/understanding-generics-in-typescript-1p7l</guid>
      <description>&lt;p&gt;&lt;em&gt;Learn how generics in TypeScript can save your time in development&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What are generics in TypeScript?
&lt;/h2&gt;

&lt;p&gt;Generics in typescript give you the advantage of writing functions or classes where that single function or class can operate with any data type like an array, string, number, or object.&lt;/p&gt;

&lt;p&gt;Ex- You want to create a stack data structure that can be used with any data type or write a custom hook for API services that returns typed data instead of “any” type.&lt;/p&gt;

&lt;h2&gt;
  
  
  Let us understand with code 🧑🏻‍💻
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Stack&amp;lt;StackType&amp;gt; {
    private items: StackType[];
    private top: number;
    constructor() {
        this.items = [];
        this.top = -1;
    }

    push(element: StackType) {
        this.items[++this.top] = element
    }

    pop() {
        return this.items[this.top--];
    }

    peek(){
        return this.items[this.top];   
    } 

    isEmpty(){
       return this.top === 0;   
    }

    size(){
        return this.top + 1;
    }
}
let stack = new Stack&amp;lt;string&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Explanation 🙇🏻‍♂️
&lt;/h2&gt;

&lt;p&gt;Here we have created a generic stack class that accepts the type argument in angle brackets “&amp;lt;&amp;gt;”. This stack class will create an items array of type parameter StackType and the push function will only accept the StackType in a parameter.&lt;/p&gt;

&lt;p&gt;Ex- If we create a number Stack by &lt;code&gt;let stack = new Stack&amp;lt;number&amp;gt;()&lt;/code&gt; then &lt;code&gt;stack.push("hello world")&lt;/code&gt; will throw an error. You can only pass numbers in the push function like &lt;code&gt;stack.push(1)&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Diving deep into generics
&lt;/h2&gt;

&lt;p&gt;There are mainly 3 main types of generics&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Generic classes&lt;/li&gt;
&lt;li&gt;Generic functions&lt;/li&gt;
&lt;li&gt;Generic constraints&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Generic classes are mainly used to create a generic data structure that can have multiple methods and variables. The type argument is passed only once in the generic class when it is instantiated.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Todo&amp;lt;TodoType&amp;gt; {
  todos: TodoType[];
  constructor() {
    this.todos = [];
  }
addTodo(todo: TodoType) {
    this.todos.push(todo);
  }
getTodos() {
    return this.todos;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Generic functions are functions that can accept any data type and return data accordingly. This makes the function more reusable and flexible.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let todos: any[] = [];
function addTodo&amp;lt;TodoType&amp;gt;(todo: TodoType) {
  todos.push(todo);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Generic constraints are very similar to generic types but it uses the extend keyword to force the user to add required parameters in a function call. The generic constraints add the constraint in the generic type function or class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function removeKey&amp;lt;Type, Key extends keyof Type&amp;gt;(obj: Type, key: Key) {
  const _obj = {...obj}
  delete _obj[key];
  return _obj;
}
function updateTodo&amp;lt;TodoType extends {
  id: number
}&amp;gt;(newTodo: TodoType) {
  todos.forEach((todo, index) =&amp;gt; {
    if(todo.id === newTodo.id) {
      todos[index] = {todo: removeKey(newTodo, "id"), id: newTodo.id}
    }
  })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the “extends” keyword ensures that the id property exists in the newTodo and we can use the id in the function to find the todo and update it accordingly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code sandbox
&lt;/h2&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/generics-typescript-dxvryl"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  How generics can help you in React?
&lt;/h2&gt;

&lt;p&gt;You can take advantage of generics in React to create generic functions, custom hooks, or generic components. I will give an example of each which can help you to write your generics.&lt;/p&gt;

&lt;h2&gt;
  
  
  Use-cases 👀
&lt;/h2&gt;

&lt;p&gt;Generic custom hook for fetching API&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const useFetch = &amp;lt;DataT&amp;gt;(api: string) =&amp;gt; {

  const [status, setStatus] = useState&amp;lt;
    "fetching" | "success" | "error"
  &amp;gt;("fetching")
  const [data, setData] = useState&amp;lt;DataT&amp;gt;();
  const [error, setError] = useState&amp;lt;string&amp;gt;();
useEffect(() =&amp;gt; {
    const fetchApi = async () =&amp;gt; {
      try {
        setStatus("fetching")
        const res = await fetch(api);
        const data = await res.json();
        setData(data);
        setStatus("success")
      } catch(err) {
        setError(err)
        setStatus("error")
      }
    }
    fetchApi();
  }, [api])

  return {data, status, error} as const;
}
const { data, status, error } = useFetch&amp;lt;{
  title: string,
  description: string,
  id: number
}&amp;gt;(API);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Generic function for creating an array of mixed data type&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createArray&amp;lt;Type&amp;gt;(
  ...values: Type[]
): Type[] {
  return [...values]
}
const myArray = createArray&amp;lt;number | string&amp;gt;(
  "Hello", "World", 2022
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Generic component that renders a list without using map&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const List = &amp;lt;T extends unknown&amp;gt;({
  data,
  keyExtractor,
  renderItem
}: {
  data: T[];
  keyExtractor: (item: T) =&amp;gt; string | number;
  renderItem: (item: T) =&amp;gt; React.ReactNode;
}) =&amp;gt; {
  return (
    &amp;lt;&amp;gt;
      {data.map((item) =&amp;gt; (
        &amp;lt;React.Fragment key={keyExtractor(item)}&amp;gt;
          {renderItem(item)}
        &amp;lt;/React.Fragment&amp;gt;
      ))}
    &amp;lt;/&amp;gt;
  );
};
&amp;lt;List
  data={data}
  keyExtractor={({ id }) =&amp;gt; id}
  renderItem={(item) =&amp;gt; &amp;lt;div&amp;gt;{item.title}&amp;lt;/div&amp;gt;}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Code sandbox
&lt;/h2&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/generics-in-react-p69s2k"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we saw how generics can help you to write more reusable functions, components, and custom hooks. We also saw the different use cases of generics that helps you to build your logic with generics in React. It also provides a very good experience with IntelliSense integration in the IDE.&lt;/p&gt;

</description>
      <category>softwaredevelopment</category>
      <category>programming</category>
      <category>devops</category>
      <category>opensource</category>
    </item>
    <item>
      <title>Custom Hooks in React</title>
      <dc:creator>Shashwat Nautiyal</dc:creator>
      <pubDate>Sun, 01 Jan 2023 08:11:19 +0000</pubDate>
      <link>https://forem.com/shashwatnautiyal/custom-hooks-in-react-49m0</link>
      <guid>https://forem.com/shashwatnautiyal/custom-hooks-in-react-49m0</guid>
      <description>&lt;p&gt;&lt;em&gt;Learn how custom hooks can help you to write clean code&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What are custom hooks?
&lt;/h2&gt;

&lt;p&gt;Hooks were introduced in React 16.8. Hooks are simple functions that allow you to use React state and lifecycle in a functional component. React has some built-in hooks that give and provide the basic functionality to use form and lifecycle.&lt;/p&gt;

&lt;p&gt;Custom hooks are user-defined functions prefixed with the “use” keyword. Depending on your logic, custom hooks may call another react hook or custom hook. It may return the function or state that re-renders the react component.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why should we use custom hooks?
&lt;/h2&gt;

&lt;p&gt;The main reasons to use customs hooks are:&lt;/p&gt;

&lt;p&gt;It helps you to separate your logic from the user interface&lt;br&gt;
It allows you to create re-usable logic blocks&lt;br&gt;
It makes your component more understandable&lt;br&gt;
It increases the modularity of your code&lt;/p&gt;
&lt;h2&gt;
  
  
  When should we use custom hooks?
&lt;/h2&gt;

&lt;p&gt;Below are some cases when you should use custom hooks&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When you are using the same logic in different components&lt;/li&gt;
&lt;li&gt;When your logic is very complex&lt;/li&gt;
&lt;li&gt;When you are working on a large-scale project&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  How should we use custom hooks?
&lt;/h2&gt;

&lt;p&gt;Before discussing how to use custom hooks, let’s discuss how to write custom hooks.&lt;/p&gt;

&lt;p&gt;We will create a basic form that persists the form data on local storage without a 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;export default function App() {
  const [firstName, setFirstName] = useState(() =&amp;gt; {
    if (localStorage.getItem("first-name"))
      return localStorage.getItem("first-name") ?? "";
    return "";
  });

  useEffect(() =&amp;gt; {
    if (firstName) {
      localStorage.setItem("first-name", firstName);
    }
  }, [firstName]);

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;h1&amp;gt;Register Now&amp;lt;/h1&amp;gt;
      &amp;lt;div className="input-wrapper"&amp;gt;
        &amp;lt;label&amp;gt;First Name&amp;lt;/label&amp;gt;
        &amp;lt;input
          value={firstName}
          onChange={(e) =&amp;gt; setFirstName(e.target.value)}
        /&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;button&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if you want to add more input fields in the form like Last Name, Email, Phone, Address, and Password, then you have to write the useEffect() hook for each field, and soon your code will get messy and very hard to maintain.&lt;/p&gt;

&lt;p&gt;Here custom hook solves this problem by extracting all the logic in the hook itself and returning the states that input fields can use.&lt;/p&gt;

&lt;p&gt;Let’s create a custom hook for this logic.&lt;br&gt;
&lt;/p&gt;

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

const useLocalStorageState = (key, state) =&amp;gt; {
  const [localState, setLocalState] = useState(() =&amp;gt; {
    if (localStorage.getItem(key))
      return JSON.parse(localStorage.getItem(key) ?? "");
    return state;
  });

  useEffect(() =&amp;gt; {
    if (localState) {
      localStorage.setItem(key, JSON.stringify(localState));
    }
  }, [localState]);

  return [localState, setLocalState];
};

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Important rules for using custom hooks
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Never call Hooks inside loops, conditions, or nested functions.&lt;/li&gt;
&lt;li&gt;Always use Hooks at the top level of your React component.&lt;/li&gt;
&lt;li&gt;Never call Hooks from regular JavaScript functions.&lt;/li&gt;
&lt;li&gt;Instead, call Hooks from React function components or call Hooks from custom Hooks.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Bonus Tip
&lt;/h2&gt;

&lt;p&gt;If you want to follow these rules without checking manually, you can use eslint-plugin-react-hooks, which automatically gives an error on your IDE.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code sandbox
&lt;/h2&gt;

&lt;p&gt;Try refreshing the code sandbox page after filling out the form.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/custom-hooks-rbcw9b"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we saw how custom hooks could help you separate your logic from the user interface and increase code reusability. We also saw the rules of hooks and how to use the custom hooks. Custom hooks can help you write more clean code and build large-scale projects.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>typescript</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
