<?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[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://aadarshthakur.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 30 Sep 2026 12:13:21 GMT</lastBuildDate><atom:link href="https://aadarshthakur.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How I built TweetSage by using chatGPT and Twitter API together]]></title><description><![CDATA[Firstly, What is TweetSage?
TweetSage is a recent project I built using Twitter API and OpenAI together to generate answers to your questions based on your recent tweets.
you can check it out live right here: TweetSage

Our website analyzes your Twit...]]></description><link>https://aadarshthakur.hashnode.dev/how-i-built-tweetsage-by-using-chatgpt-and-twitter-api-together</link><guid isPermaLink="true">https://aadarshthakur.hashnode.dev/how-i-built-tweetsage-by-using-chatgpt-and-twitter-api-together</guid><category><![CDATA[Next.js]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[Twitter]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Aadarsh Thakur]]></dc:creator><pubDate>Mon, 19 Dec 2022 17:09:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1671450403773/g5Mwnw9yL.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-firstly-what-is-tweetsage">Firstly, What is TweetSage?</h1>
<p>TweetSage is a recent project I built using Twitter API and OpenAI together to generate answers to your questions based on your recent tweets.</p>
<p>you can check it out live right here: <a target="_blank" href="https://tweet-sage.vercel.app/">TweetSage</a></p>
<blockquote>
<p>Our website analyzes your Twitter activity to provide you with accurate and relevant responses to your queries</p>
</blockquote>
<h2 id="heading-how-does-it-work">How does it work?</h2>
<p>It is built on a very simple idea. Let me explain it to you based on the 2 steps that our website uses.</p>
<h3 id="heading-first-step">First Step</h3>
<ul>
<li>We ask for a Twitter Username, you can provide any Twitter user's username, It doesn't have to be yours only</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671450647355/p-hC80UrV.png" alt class="image--center mx-auto" /></p>
<p>After you provide us with a username, we use that username to fetch that user's recent tweets using Twitter's official API.</p>
<h3 id="heading-second-step">Second Step</h3>
<ul>
<li>We ask you to type a question that you would like to be answered</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671450849706/yArpdfSjk.png" alt class="image--center mx-auto" /></p>
<p>As you provide us with a question, we provide all the tweets along with your question to the chatGPT API and chatGPT simply answers your question based on those tweets provided along with the question and renders the generated answer on the screen</p>
<h1 id="heading-now-that-you-have-an-idea-about-how-the-website-works-lets-hop-on-to-how-to-code-it">Now that you have an idea about how the website works, Let's hop on to how to code it</h1>
<h3 id="heading-tech-stack-used">Tech stack used:</h3>
<ul>
<li><p>NextJS13</p>
</li>
<li><p>Typescript</p>
</li>
<li><p>TailwindCSS</p>
</li>
<li><p>MaterialUI</p>
</li>
<li><p>Twitter API SDK client</p>
</li>
<li><p>OpenAI library</p>
</li>
</ul>
<p>Let's start with setting up your nextJS app (I'm using the nextJS 13 experimental beta version here)</p>
<h2 id="heading-1-create-a-nextjs-app">1. Create a nextJS app</h2>
<pre><code class="lang-sh">npx create-next-app@latest --experimental-app &lt;your project name&gt;
</code></pre>
<p>create-next-app now ships with TypeScript by default so we'll be working with typescript in this project</p>
<h2 id="heading-2-cd-into-the-app-and-lets-install-all-the-dependencies-were-gonna-use">2. cd into the app and let's install all the dependencies we're gonna use</h2>
<p>Twitter SDK client:<br /><code>npm install twitter-api-sdk</code></p>
<p>OpenAI :<br /><code>npm install openai</code></p>
<p>I'm not gonna cover the UI part so we can skip installing tailwindCSS and materialUI</p>
<h2 id="heading-3-lets-start-with-setting-up-our-twitter-and-openai-clients">3. Let's start with setting up our Twitter and OpenAI clients</h2>
<p>We will also be setting up API endpoints to fetch data from the clients using nextJS API routes to create those API endpoints</p>
<p>Create two files in your <code>/pages/api</code> directory named <code>tweets.ts</code> and <code>ai.ts</code></p>
<p>In <code>/tweets.ts</code></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Client } <span class="hljs-keyword">from</span> <span class="hljs-string">"twitter-api-sdk"</span>;
</code></pre>
<p>and create a client like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> (req: NextApiRequest, res: NextApiResponse) =&gt; {
    <span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> Client(process.env.BearerToken!);
}
</code></pre>
<p><code>BearerToken</code> is a token that Twitter API provides you when you set up for Twitter developer account</p>
<p>you can get your API <a target="_blank" href="https://developer.twitter.com/en/products/twitter-api">here</a></p>
<p>Now let's fetch the user's tweets using the client</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> client.tweets.tweetsRecentSearch({
      query: <span class="hljs-string">`(from:<span class="hljs-subst">${req.body.user}</span>) -is:retweet -is:reply -is:quote`</span>,
      max_results: <span class="hljs-number">10</span>,
      expansions: [<span class="hljs-string">"author_id"</span>],
      <span class="hljs-string">"user.fields"</span>: [
        <span class="hljs-string">"name"</span>,
        <span class="hljs-string">"profile_image_url"</span>,
      ],
    });
    res.status(<span class="hljs-number">200</span>).json({ data });
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.log(err);
  }
</code></pre>
<p><code>req.body.user</code> here represents the username that we'll put in our form input field This is a boilerplate code that Twitter API provides to fetch different results, in this request we're fetching the user's Twitter username, profile picture and their recent tweets.</p>
<p>Let's setup openAI now, in <code>/api/ai.ts</code> let's import two things from openAI and create openAI client</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> configuration = <span class="hljs-keyword">new</span> Configuration({
  apiKey: process.env.OPEN_API_KEY,
});
<span class="hljs-keyword">const</span> openai = <span class="hljs-keyword">new</span> OpenAIApi(configuration);
</code></pre>
<p>You can get your <code>OPEN_API_KEY</code> in <a target="_blank" href="https://openai.com/api/">here</a></p>
<p>Let's fetch our answer now</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> (req: NextApiRequest, res: NextApiResponse) =&gt; {
  <span class="hljs-keyword">const</span> completion = <span class="hljs-keyword">await</span> openai.createCompletion({
    model: <span class="hljs-string">"text-davinci-003"</span>,
    prompt: req.body.prompt,
    temperature: <span class="hljs-number">1</span>,
    top_p: <span class="hljs-number">1</span>,
    frequency_penalty: <span class="hljs-number">0</span>,
    presence_penalty: <span class="hljs-number">0</span>,
    max_tokens: <span class="hljs-number">256</span>,
  });

  res.status(<span class="hljs-number">200</span>).json({ result: completion.data });
};
</code></pre>
<p>Now here 'req.body.prompt` is not our question here, it's our question along with all the tweets we fetched in the previous point using the Twitter API</p>
<p>Okay so let's see how we will create our <code>prompt</code> in the next step</p>
<h2 id="heading-4-creating-a-prompt-for-openai">4. Creating a Prompt for OpenAI</h2>
<p>You can create a basic form with an input field along with a submit button with a handleClick function which we will use to fetch tweets and use a state to store those tweets</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> TweetData = {
  text: <span class="hljs-built_in">string</span> | <span class="hljs-literal">null</span> | <span class="hljs-literal">undefined</span>;
};

<span class="hljs-keyword">const</span> [tweets, setTweets] = useState&lt;TweetData[]&gt;([]);

<span class="hljs-keyword">const</span> handleClick = <span class="hljs-keyword">async</span> (e: MouseEvent&lt;HTMLButtonElement&gt;) =&gt; {
    e.preventDefault();

    <span class="hljs-keyword">if</span> (user === <span class="hljs-string">""</span>) {
      <span class="hljs-keyword">return</span>;
    }
    setLoadingTweets(<span class="hljs-literal">true</span>);

    <span class="hljs-keyword">const</span> results = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"/api/user/tweets"</span>, {
      method: <span class="hljs-string">"POST"</span>,
      body: <span class="hljs-built_in">JSON</span>.stringify({
        user,
      }),
      headers: {
        <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
      },
    }).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json());

    setTweets(results.data.data);
  };
</code></pre>
<p>Now that we have our tweets, let's create our next input field for a question and a submit button with another handleClick function to fetch our answer</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> [answer, setAnswer] = useState&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">""</span>);

<span class="hljs-keyword">const</span> handleGetData= <span class="hljs-keyword">async</span> (e: MouseEvent&lt;HTMLButtonElement&gt;) =&gt; {
    e.preventDefault();

    <span class="hljs-keyword">if</span> (question === <span class="hljs-string">""</span>) {
      <span class="hljs-keyword">return</span>;
    }
    setLoadingData(<span class="hljs-literal">true</span>);

    <span class="hljs-keyword">const</span> prompt = <span class="hljs-string">`you are given some tweets below, read these tweets : \n
      <span class="hljs-subst">${tweets.map((tweet) =&gt; tweet.text + <span class="hljs-string">"\n"</span>)}</span>
      and about the person who wrote those Tweets <span class="hljs-subst">${question}</span>
      `</span>;

    <span class="hljs-comment">// fetch data function</span>
  };
</code></pre>
<p>Before we look into the fetch data function, let's look at how the <code>prompt</code> is created here We have set up a simple string as you can see above that says :</p>
<p>"you are given some tweets below, read these tweets" then we map over all the tweets we fetched and provide those tweets in the string and then we add "and about the person who wrote those Tweets ${question}" <code>question</code> here refers to the question we are asking the user to fill in the question input form</p>
<p>How it looks all combined: "you are given some tweets below, read these tweets</p>
<p>&lt;tweet no. 1&gt; &lt;tweet no. 2&gt; . . . &lt;tweet no. 10&gt; and about the person who wrote those Tweets " write 5 points "</p>
<p>Now let's fetch data using this prompt</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> results = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"/api/user/ai"</span>, {
      method: <span class="hljs-string">"POST"</span>,
      body: <span class="hljs-built_in">JSON</span>.stringify({
        prompt,
      }),
      headers: {
        <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
      },
    }).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json());

    setAnswer(results.result.choices[<span class="hljs-number">0</span>].text);
</code></pre>
<h2 id="heading-5-now-all-that-remains-is-rendering-the-data-onto-the-users-screen">5. Now all that remains is rendering the data onto the user's screen</h2>
<p>We can simply take our <code>answer</code> state with the generated answer and display it into a <code>div</code> element, you can even make a typing effect to write the answer to look cooler, like how I used it in TweetSage</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671454331223/sxwvZkndy.gif" alt class="image--center mx-auto" /></p>
<h1 id="heading-final-notes">Final Notes</h1>
<p>If you wanna look into the code on how to add the typing effect or any other code you can simply go to the project's <a target="_blank" href="https://github.com/Aadarsh805/TweetSage">GitHub repository</a>, all the code is open source and is public for you to use.</p>
<p>The project is also open for contributions, you can open and add a new feature or you can also submit a bug that you found using the project.</p>
<p>I think that's it for this blog, hope you find this blog helpful and that you build something awesome too using the awesome chatGPT API</p>
<p>If you have any questions, reach out to me on my <a target="_blank" href="https://twitter.com/Aadarsh805">Twitter</a></p>
<p>Thanks for reading till the last, would love it if you go to the <a target="_blank" href="https://tweet-sage.vercel.app/">live website</a> and try TweetSage yourself, and would love it even more if you could go and star our TweetSage <a target="_blank" href="https://github.com/Aadarsh805/TweetSage">repo</a> on Github.</p>
]]></content:encoded></item><item><title><![CDATA[ZOD - TypeScript-first schema data validation]]></title><description><![CDATA[Do you guys know that Typescript only does type-checking at compile time and no runtime checks?
Well, why do we even need runtime checks after typescript compile time checks, well the first use could be validating data on the server side, which types...]]></description><link>https://aadarshthakur.hashnode.dev/zod-typescript-first-schema-data-validation</link><guid isPermaLink="true">https://aadarshthakur.hashnode.dev/zod-typescript-first-schema-data-validation</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[zod]]></category><category><![CDATA[WeMakeDevs]]></category><dc:creator><![CDATA[Aadarsh Thakur]]></dc:creator><pubDate>Tue, 13 Dec 2022 10:11:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670926152787/wVcQ9tgjQ.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Do you guys know that Typescript only does type-checking at compile time and no runtime checks?</p>
<p>Well, why do we even need runtime checks after typescript compile time checks, well the first use could be validating data on the server side, which typescript has no idea of at compile time.</p>
<p>we can't always be sure about what type of variables we'll get from external sources like APIs or form inputs.</p>
<p>For example, when we have some form to be filled, Typescript can't guarantee the user-filled inputs to be 100% type correct as we want on our database.</p>
<h1 id="heading-what-is-zod-and-why-do-we-need-it">What is Zod and why do we need it?</h1>
<p>Zod is a tool that solves this problem. It fills this TypeScript blindspot and helps with type safety during runtime by having an additional runtime check.</p>
<blockquote>
<p>Zod is a TypeScript-first schema declaration and validation library. It provides safety checks at runtime working in conjunction with Typescript!</p>
</blockquote>
<h1 id="heading-installation">Installation</h1>
<p>Zod can be installed into your react application using npm or yarn</p>
<p><code>npm install zod</code></p>
<p><code>yarn add zod</code></p>
<h3 id="heading-requirements">Requirements</h3>
<ul>
<li>TypeScript 4.5+!</li>
<li><code>strict</code> mode must be enabled in your <code>tsconfig.json</code> file<pre><code><span class="hljs-comment">// tsconfig.json</span>
{
  <span class="hljs-string">"compilerOptions"</span>: {
    <span class="hljs-string">"strict"</span>: <span class="hljs-literal">true</span>
  }
}
</code></pre></li>
</ul>
<h1 id="heading-usage">Usage</h1>
<p>Let's string by creating a very simple string schema using zod</p>
<pre><code><span class="hljs-keyword">import</span> { z } <span class="hljs-keyword">from</span> <span class="hljs-string">"zod"</span>;

<span class="hljs-keyword">const</span> stringSchema = z.string().min(<span class="hljs-number">10</span>).max(<span class="hljs-number">15</span>);

stringSchema.parse(<span class="hljs-string">"example string"</span>)
</code></pre><p>This will be safely parsed as it follows the zod schema we used to parse it.</p>
<p>But if we try something that outflows the schema parsing instructions, such as </p>
<pre><code>stringSchema.parse(<span class="hljs-string">"string of much greater length"</span>)
</code></pre><p>This will throw an error</p>
<pre><code>{
      <span class="hljs-attr">code</span>: <span class="hljs-string">'too_big'</span>,
      <span class="hljs-attr">maximum</span>: <span class="hljs-number">15</span>,
      <span class="hljs-attr">type</span>: <span class="hljs-string">'string'</span>,
      <span class="hljs-attr">inclusive</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'String must contain at most 15 characters,
      path: []
    }</span>
</code></pre><p>Zod also provides various other methods such as </p>
<pre><code>z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.symbol();

<span class="hljs-comment">// empty types</span>
z.undefined();
z.null();
z.void(); <span class="hljs-comment">// accepts undefined</span>

<span class="hljs-comment">// catch-all types</span>
<span class="hljs-comment">// allows any value</span>
z.any();
z.unknown();

<span class="hljs-comment">// never type</span>
<span class="hljs-comment">// allows no values</span>
z.never();
</code></pre><h1 id="heading-objects-in-zod">Objects in zod</h1>
<p>Objects can be used extensively whether they be validating a user form or fetching data from an API</p>
<p>Let's take an example for validating a user form data</p>
<pre><code><span class="hljs-keyword">const</span> userData = z.object({
  <span class="hljs-attr">firstName</span>: z.string().min(<span class="hljs-number">1</span>).max(<span class="hljs-number">10</span>),
  <span class="hljs-attr">lastName</span>: z.string().min(<span class="hljs-number">1</span>).max(<span class="hljs-number">10</span>),
  <span class="hljs-attr">email</span>: z.string().email(),
})
</code></pre><h1 id="heading-zod-to-parse-api-data">zod to parse API data</h1>
<p>In this example let's fetch data from the random user API and validate it using zod</p>
<pre><code><span class="hljs-keyword">const</span> randomUsers = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://swapi.dev/api/people/"</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json(),
  );
};
</code></pre><p>Now this would return an array of users, we can parse the result using the <code>z.array()</code> method</p>
<pre><code>  <span class="hljs-keyword">const</span> randomUsers = z.object({
  <span class="hljs-attr">results</span>: z.array(z.object()),
});

  <span class="hljs-keyword">const</span> parsedData = randomUsers.parse(data);

  <span class="hljs-keyword">return</span> parsedData.results;
</code></pre><p>Here we are declaring that the <code>results</code> array could be of any object type, we can further specify the data inside the result array to be of the <code>user</code> type like this</p>
<pre><code>  <span class="hljs-keyword">const</span> randomUser = z.object({
      <span class="hljs-attr">name</span>: z.object({
        <span class="hljs-attr">first</span>: z.string(),
        <span class="hljs-attr">last</span>: z.string()
      })
  })

<span class="hljs-comment">// declare the type of results array to be randomUser</span>

  <span class="hljs-keyword">const</span> randomUsers = z.object({
  <span class="hljs-attr">results</span>: z.array(randomUser),
});

  <span class="hljs-keyword">const</span> parsedData = randomUsers.parse(data);

  <span class="hljs-keyword">return</span> parsedData.results;
</code></pre><h1 id="heading-make-schema-values-optional">Make schema values optional</h1>
<p>What if we want our email input to be optional here, we can do it as such by adding <code>.optional()</code> to the end of our email schema: </p>
<pre><code><span class="hljs-keyword">const</span> userData = z.object({
  <span class="hljs-attr">firstName</span>: z.string().min(<span class="hljs-number">1</span>).max(<span class="hljs-number">10</span>),
  <span class="hljs-attr">lastName</span>: z.string().min(<span class="hljs-number">1</span>).max(<span class="hljs-number">10</span>),
  <span class="hljs-attr">email</span>: z.string().email().optional(),
})
</code></pre><h1 id="heading-default-value-in-the-schema">Default value in the schema</h1>
<p>What if we want <code>email</code> to be optional but don't want it to be undefined in our database, we can do so by passing a default value in its place by adding <code>.default()</code> to the end of our email schema: </p>
<pre><code><span class="hljs-keyword">const</span> userData = z.object({
  <span class="hljs-attr">firstName</span>: z.string().min(<span class="hljs-number">1</span>).max(<span class="hljs-number">10</span>),
  <span class="hljs-attr">lastName</span>: z.string().min(<span class="hljs-number">1</span>).max(<span class="hljs-number">10</span>),
  <span class="hljs-attr">email</span>: z.string().email().default(<span class="hljs-string">"default@gmail.com"</span>),
})
</code></pre><h1 id="heading-reducing-duplicate-values-by-composing-schemas">Reducing Duplicate values by composing schemas</h1>
<p>Suppose we have this schema with <code>User</code>, <code>Post</code>, <code>Comment</code></p>
<pre><code><span class="hljs-keyword">const</span> User = z.object({
  <span class="hljs-attr">id</span>: z.string().uuid(),
  <span class="hljs-attr">name</span>: z.string(),
});

<span class="hljs-keyword">const</span> Post = z.object({
  <span class="hljs-attr">id</span>: z.string().uuid(),
  <span class="hljs-attr">title</span>: z.string(),
});

<span class="hljs-keyword">const</span> Comment = z.object({
  <span class="hljs-attr">id</span>: z.string().uuid(),
  <span class="hljs-attr">comment</span>: z.string(),
});
</code></pre><p>Notice that <code>id</code> is repeated in every schema</p>
<p>A very basic solution could be placing id in its own type and other schemas can use that reference.</p>
<pre><code><span class="hljs-keyword">const</span> Id = z.string().uuid();

<span class="hljs-keyword">const</span> User = z.object({
  <span class="hljs-attr">id</span>: Id,
  <span class="hljs-attr">name</span>: z.string(),
});

<span class="hljs-keyword">const</span> Post = z.object({
  <span class="hljs-attr">id</span>: Id,
  <span class="hljs-attr">title</span>: z.string(),
  <span class="hljs-attr">body</span>: z.string(),
});

<span class="hljs-keyword">const</span> Comment = z.object({
  <span class="hljs-attr">id</span>: Id,
  <span class="hljs-attr">text</span>: z.string(),
});
</code></pre><p>But this is still quite repetitive, Another solution can be by using the <code>extend</code> method.</p>
<p>We can create a base object schema with id and then extend all other schema and add to the base schema as such: </p>
<pre><code><span class="hljs-keyword">const</span> schemaWithId = z.object({
  <span class="hljs-attr">id</span>: z.string().uuid()
});

<span class="hljs-keyword">const</span> User = ObjectWithId.extend({
  <span class="hljs-attr">name</span>: z.string(),
});

<span class="hljs-keyword">const</span> Post = ObjectWithId.extend({
  <span class="hljs-attr">title</span>: z.string(),
});

<span class="hljs-keyword">const</span> Comment = ObjectWithId.extend({
  <span class="hljs-attr">comment</span>: z.string(),
});
</code></pre><p>now we can add multiple values directly to share between all the objects</p>
<pre><code><span class="hljs-keyword">const</span> schemaWithId = z.object({
  <span class="hljs-attr">id</span>: z.string().uuid(),
  <span class="hljs-attr">createdAt</span>: z.datetime()
});
</code></pre><p>Both <code>id</code> and <code>createdAt</code> values will be shared between all the objects.</p>
<h1 id="heading-transform-data-within-the-schema">Transform Data within the schema</h1>
<p>Let's take back the random user but with a slight change that we are receiving <code>fullName</code> instead of separate <code>firstName</code> and <code>lastName</code> but and we want to split the <code>fullName</code> value into <code>firstName</code> and <code>lastName</code></p>
<p>This can be done by transforming the <code>fullName</code> value by splitting it at the <code>" "</code> blank space within the schema by using the <code>transform</code> method</p>
<pre><code><span class="hljs-keyword">const</span> userData = z.object({
  <span class="hljs-attr">fullName</span>: z.string()
})
  .transform(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> ({
      ...user,
      <span class="hljs-attr">nameAsArray</span>: user.name.split( <span class="hljs-string">" "</span> ),  
  }));
</code></pre><p>the <code>transform</code> method can be used in various ways to transform that data within the schema.</p>
<h1 id="heading-type-inference">Type Inference</h1>
<p>Suppose we already have defined our schema somewhere and want to use the same schema definition somewhere else without rewriting the schema again, we can do such by extracting its typescript type.</p>
<p>We can extract the TypeScript type of any schema with <code>z.infer&lt;typeof schema&gt;</code> </p>
<pre><code>
<span class="hljs-keyword">const</span> user = z.object({
  <span class="hljs-attr">name</span>: z.string(),
  <span class="hljs-attr">age</span>: z.number(),
});

type userType = z.infer&lt;<span class="hljs-keyword">typeof</span> user&gt;;
</code></pre><p>zod is a very easy library to implement and having both compile time and runtime checks will even boost your application's performance.</p>
<p>I hope these help you to get a basic understanding of how zod works. zod is much more than just this, to learn and understand much more about zod, use these official <a target="_blank" href="https://github.com/colinhacks/zod">docs</a>  </p>
<p>Thanks for reading till the last</p>
<p>Reach me on <a target="_blank" href="https://twitter.com/Aadarsh805">Twitter</a></p>
]]></content:encoded></item><item><title><![CDATA[Typescript types in react]]></title><description><![CDATA[Typescript
TypeScript is a free, open-source programming language developed and maintained by Microsoft. 
It comes with static type checking which helps you to learn about potential bugs as you're typing the code other than heading to the browser and...]]></description><link>https://aadarshthakur.hashnode.dev/typescript-types-in-react</link><guid isPermaLink="true">https://aadarshthakur.hashnode.dev/typescript-types-in-react</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[BlogsWithCC]]></category><dc:creator><![CDATA[Aadarsh Thakur]]></dc:creator><pubDate>Wed, 09 Nov 2022 11:44:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1667901304905/6nlyol2H4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-typescript">Typescript</h1>
<p>TypeScript is a free, open-source programming language developed and maintained by Microsoft. 
It comes with static type checking which helps you to learn about potential bugs as you're typing the code other than heading to the browser and figuring it out at runtime.</p>
<blockquote>
<p>Typescript is an initial investment that pays off in the long run. The benefits of learning typescript outweigh the time you spend on learning it.</p>
</blockquote>
<h1 id="heading-typescript-with-react">Typescript with react</h1>
<p>TypeScript can be helpful to React developers in many ways. I'm listing all the basic typescript types you should know to work with typescript in your react project.</p>
<h3 id="heading-installation">Installation</h3>
<p>Setup react project with typescript support using create-react-app</p>
<pre><code>npx create-react-app name-<span class="hljs-keyword">of</span>-app --template typescript
</code></pre><h1 id="heading-props-types">Props types</h1>
<p>Checking the type of props helps a lot so that you cannot pass any undesirable values in your props.</p>
<h3 id="heading-1-string-prop-type">1. string prop type</h3>
<p>Example: </p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params">props</span>)</span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome, {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre><p>In the above code snippet we can setup a strict typescript type to the name props so that nothing other that string can be passed onto the name prop. This is how we do it : </p>
<pre><code><span class="hljs-comment">// Declaring type of name prop</span>
type MyPropType = {
  <span class="hljs-attr">name</span>: string
}

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">(<span class="hljs-params">props: MyPropType</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Welcome, {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre><p>This will make sure that the name prop only receives a string type value, if you try to pass any other type it will through an error and won't compile.</p>
<p>Extra benefit: 
You get an autocomplete feature with props as typescript now know that props can only receive the declared values in propType.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667901416000/Le4pxxCyo.png" alt="Screenshot from 2022-11-08 15-26-43.png" /></p>
<h3 id="heading-2-object-props-type">2. object props type</h3>
<pre><code><span class="hljs-comment">// an object name with first and last keys</span>
type ObjectPropType = {
  <span class="hljs-attr">name</span>: {  
     <span class="hljs-attr">first</span>: string  
     <span class="hljs-attr">last</span>: string
  }
}

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">(<span class="hljs-params">props: ObjectPropType</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome, {props.name.first} {props.name.last}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre><h3 id="heading-3-array-prop-type">3. Array prop type</h3>
<pre><code><span class="hljs-comment">// an array of object names</span>
type ArrayPropType = {
  <span class="hljs-attr">name</span>: {
    <span class="hljs-attr">first</span>: string
    <span class="hljs-attr">last</span>: string
  }[]   <span class="hljs-comment">// by adding '[]' it is declared as an array type of objects</span>
}
</code></pre><h3 id="heading-add-more-strict-values-to-props">Add more strict values to props</h3>
<p>if we want our props to receive a particular set of strings instead of any strings we can do as: </p>
<pre><code>type StrictProps = {
  <span class="hljs-attr">status</span>: <span class="hljs-string">'Loading'</span> | <span class="hljs-string">'Success'</span> | <span class="hljs-string">'Error'</span> 
}
</code></pre><p>with this implicit declaring of values for the status prop, no other string other than 'loading', 'success', or 'error' will be accepted by typescript.</p>
<h3 id="heading-4-children-props-type">4. Children props type</h3>
<p>We can even type check for children inside our component</p>
<pre><code><span class="hljs-comment">// passing props as children</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span>&gt;</span>Aadarsh<span class="hljs-tag">&lt;/<span class="hljs-name">MyComponent</span>&gt;</span></span>
  )
}

type ChildrenPropsType = {
  <span class="hljs-attr">children</span>: string
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params">props: ChildrenPropsType</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{props.children}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre><h3 id="heading-5-react-component-as-children-prop-type">5. React component as children prop type</h3>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">AnotherComponent</span> /&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">MyComponent</span>&gt;</span></span>
  )    
}

type ComponentAsChildrenProps = {
  <span class="hljs-attr">children</span>: React.ReactNode
}
<span class="hljs-comment">// ReactNode type is the type of react components</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params">props: ComponentAsChildrenProps</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{props.children}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre><h3 id="heading-6-optional-props">6. Optional Props</h3>
<p>Typescript makes you pass every prop declared in the prop type by default, we can make some props optional using the '?' operator</p>
<pre><code><span class="hljs-comment">// an object name with first and last keys</span>
type OptionalPropType = {
  <span class="hljs-attr">name</span>: {  
     <span class="hljs-attr">first</span>: string  
     last?: string <span class="hljs-comment">// last name might not be provided by the upper component</span>
  }
}

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">(<span class="hljs-params">props: OptionalPropType</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome, {props.name.first} {props.name?.last}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span> 
  <span class="hljs-comment">// here we will need to use name.last as name?.last because last variable is optional as     </span>
  <span class="hljs-comment">//might be undefined</span>
}
</code></pre><h3 id="heading-7-function-as-props">7. function as props</h3>
<pre><code>type functionPropType = {
  <span class="hljs-attr">handleClick</span> : <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">void</span>  <span class="hljs-comment">// return type can be declared as void or string or any other type</span>
}
</code></pre><h3 id="heading-8-event-props-type">8. Event props type</h3>
<h4 id="heading-onclick-event">onClick event:</h4>
<pre><code>type EventPropType = {
  <span class="hljs-attr">handleClick</span> : <span class="hljs-function">(<span class="hljs-params">event: React.MouseEvent&lt;HTMLButtonElement&gt;</span>) =&gt;</span> <span class="hljs-keyword">void</span>  
  <span class="hljs-comment">// further strict check that event is from a button HTML element</span>
}

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">(<span class="hljs-params">props: EventPropType</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{props.handleClick}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
}
</code></pre><h4 id="heading-onchange-event">onChange event:</h4>
<pre><code>type EventPropType = {
  <span class="hljs-attr">value</span>: string
  <span class="hljs-attr">handleChange</span> : <span class="hljs-function">(<span class="hljs-params">event: React.ChangeEvent&lt;HTMLInputElement&gt;</span>) =&gt;</span> <span class="hljs-keyword">void</span>  
  <span class="hljs-comment">// further strict check that event is from a input HTML element</span>
}

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">(<span class="hljs-params">props: EventPropType</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{props.value}</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{props.handleChange}</span> /&gt;</span></span>
}
</code></pre><h3 id="heading-9-style-props">9. Style props</h3>
<pre><code>type StyleProps = {
  <span class="hljs-attr">styles</span>: React.CSSProperties
}
</code></pre><h1 id="heading-hooks">Hooks</h1>
<h2 id="heading-1-usestate-hook">1. useState hook</h2>
<p>type inference for use state assigns type itself to a state provided a given initial value.</p>
<pre><code><span class="hljs-keyword">const</span> [state, setState] = useState(<span class="hljs-literal">false</span>)
<span class="hljs-comment">// `state` is inferred to be a boolean</span>
<span class="hljs-comment">// `setState` only takes booleans</span>
</code></pre><p>However, for states being assigned null value initially will need type declared for future assignable value</p>
<pre><code>type UserType = {
  <span class="hljs-attr">name</span>: {
    <span class="hljs-attr">first</span>: string
    <span class="hljs-attr">last</span>: string
  }
  <span class="hljs-attr">email</span>: string
}
<span class="hljs-keyword">const</span> [user, setUser] = useState&lt;UserType | <span class="hljs-literal">null</span>&gt;(<span class="hljs-literal">null</span>) 
<span class="hljs-comment">// declaring that user can be of userType in future with null value in present</span>
</code></pre><p>For future state which will be initialized soon after setup and will never have null assigned you can write such condition as such: </p>
<pre><code><span class="hljs-keyword">const</span> [user, setUser] = useState&lt;userType&gt;({} <span class="hljs-keyword">as</span> userType)
</code></pre><p>This is kind of lying to the compiler that '{}' also is of type userType</p>
<h2 id="heading-2-usereducer-hook">2. useReducer hook</h2>
<p>we can setup types of useReducer actions and state. </p>
<p>a simple counter using useReducer hook for example: </p>
<pre><code>type StateType = {
  <span class="hljs-attr">count</span>: number
}

type ActionType = {
  <span class="hljs-attr">type</span> : string
  <span class="hljs-attr">payload</span>: number
}

<span class="hljs-keyword">const</span> initialState = { 
  <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> 
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state: StateType, action: ActionType</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"increment"</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count + action.payload };
    <span class="hljs-keyword">case</span> <span class="hljs-string">"decrement"</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count - action.payload };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initialState);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      Count: {state.count}
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: "decrement", payload: 1 })}&gt;
        decrement by 1
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: "increment", payload: 1 })}&gt;
        increment by 1
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre><p>we can further strict action type to not be just any string but only increment and decrement</p>
<pre><code>type ActionType = {
  <span class="hljs-attr">type</span>: <span class="hljs-string">'increment'</span> | <span class="hljs-string">'decrement'</span>
  <span class="hljs-attr">payload</span>: number
}
</code></pre><p>what if you now have a third button for reset</p>
<pre><code>&lt;button onClick={<span class="hljs-function">() =&gt;</span> dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"reset"</span>})}&gt;
        reset to <span class="hljs-number">0</span>
&lt;/button&gt;
</code></pre><p>as you can see this dispatch function doesn't have a payload property in it, typescript will throw error here saying 'payload not initialized'</p>
<p>there's two ways to deal with this either so make payload as an optional variable</p>
<pre><code>type ActionType = {
  <span class="hljs-attr">type</span>: <span class="hljs-string">'increment'</span> | <span class="hljs-string">'decrement'</span>
  payload?: number <span class="hljs-comment">// now payload is optional</span>
}
</code></pre><p>or another better way, you set up different types for update and reset functions like this</p>
<pre><code>type UpdateCountActionType = {
  <span class="hljs-attr">type</span>: <span class="hljs-string">'increment'</span> | <span class="hljs-string">'decrement'</span>
  <span class="hljs-attr">payload</span>: number
}

type ResetCountActionType = {
  <span class="hljs-attr">type</span>: <span class="hljs-string">'reset'</span>
  <span class="hljs-comment">// without payload</span>
}

<span class="hljs-comment">// now you can set your action type as</span>
type actionType = UpdateCountActionType | ResetCountActionType 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state: StateType, action: ActionType</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"increment"</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count + action.payload };
    <span class="hljs-keyword">case</span> <span class="hljs-string">"decrement"</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count - action.payload };
    <span class="hljs-keyword">case</span> <span class="hljs-string">"reset"</span> :
      <span class="hljs-keyword">return</span> initialState;
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state
  }
}
</code></pre><h2 id="heading-3-useref-hook">3. useRef hook</h2>
<p>while using useRef hook typescript expects us to write the type of the element being assigned to that ref</p>
<pre><code><span class="hljs-keyword">const</span> inputRef = useRef&lt;HTMLInputElement&gt;(<span class="hljs-literal">null</span>!);
 <span class="hljs-comment">// the '!' with null is used to indicate that the element is not going to be null</span>

<span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span></span>
);
</code></pre><h2 id="heading-4-usecontext-hook">4. useContext hook</h2>
<p>Example: Defining a context passing down a user as value</p>
<pre><code>
type UserType = {
  <span class="hljs-attr">name</span>: string
  <span class="hljs-attr">email</span>: string
}

type ContextType = {
  <span class="hljs-attr">user</span>: UserType | <span class="hljs-literal">null</span>
  <span class="hljs-attr">setUser</span>: React.Dispatch&lt;React.SetStateAction&lt;UserType | <span class="hljs-literal">null</span>&gt;&gt;
}

type ChildrenType = {
  <span class="hljs-attr">children</span>: React.ReactNode
}

<span class="hljs-keyword">const</span> StateContext = createContext&lt;ContextType | <span class="hljs-literal">null</span>&gt;(<span class="hljs-literal">null</span>)

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> StateProvider = <span class="hljs-function">(<span class="hljs-params">{children} : ChildrenType</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> [user, setUser] = useState&lt;UserType | <span class="hljs-literal">null</span>&gt;(<span class="hljs-literal">null</span>)

<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">StateContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{user,</span> <span class="hljs-attr">setUser</span>}}&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">StateContext.Provider</span>&gt;</span></span>
}
</code></pre><p>you can get the type of setUser function by hovering over it </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667993051344/Jz5wnEQCK.png" alt="Screenshot from 2022-11-09 16-53-41.png" /></p>
<hr />

<p>Alright, that's a wrap, we covered all the basic react typescript types, there's still a lot to typescript than this. If you wanna learn further ahead head to the <a target="_blank" href="https://www.typescriptlang.org/docs/">typescript official docs</a>.</p>
<p>I hope these help you to get a basic understanding of how typescript types are used in react.</p>
<p>Thanks for reading till the last</p>
<p>Reach me on <a target="_blank" href="https://twitter.com/Aadarsh805">Twitter</a></p>
]]></content:encoded></item><item><title><![CDATA[Top  6  MaterialUI components for you to use in your next project]]></title><description><![CDATA[You have a great project idea in mind but you are too lazy to build those repeating utility components from scratch every time. Well, that's where UI component libraries such as MaterialUI come in great use. These libraries provide predefined and cus...]]></description><link>https://aadarshthakur.hashnode.dev/top-6-materialui-components-for-you-to-use-in-your-next-project</link><guid isPermaLink="true">https://aadarshthakur.hashnode.dev/top-6-materialui-components-for-you-to-use-in-your-next-project</guid><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Aadarsh Thakur]]></dc:creator><pubDate>Thu, 03 Nov 2022 11:02:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1666532164235/NyFqIOCzu.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You have a great project idea in mind but you are too lazy to build those repeating utility components from scratch every time. Well, that's where UI component libraries such as MaterialUI come in great use. These libraries provide predefined and customizable utility components which would take a lot of your precious time if built from scratch, using these prebuilt components will let you focus more on other important parts of your project.</p>
<h1 id="heading-introduction-to-materialui">Introduction to MaterialUI</h1>
<p>MaterialUI is a free and open-source react library based on Google's material design which is maintained by MUI. MaterialUI provides predefined and customizable react UI components to make UI development much easier, speeding up the web design process.</p>
<p>MaterialUI provides different varieties of predefined components such as a navbar, text fields, layout components such as Grid, etc. 
I'm gonna list the 6 MUI components that I find the coolest which you can use in your next project along with a short description of how to use them.</p>
<h1 id="heading-installation">Installation</h1>
<p>First, you need to have the mui library installed in your react app. You can install it using npm or yarn</p>
<p>npm : <code>npm install @mui/material @emotion/react @emotion/styled</code></p>
<p>yarn: <code>yarn add @mui/material @emotion/react @emotion/styled</code></p>
<p>Now that you have materialUI installed let's start with our first mui component</p>
<h1 id="heading-1-mui-grid">1. MUI Grid</h1>
<p>MaterialUI provides an amazing grid system for responsive web designs. Mui's responsive grid system is based on a 12-column grid layout. It allows visual consistency across multiple screen sizes and inputs.</p>
<ul>
<li>The grid container is implemented using the  component with the 'container' variant and items are declared using </li>
<li>Items' widths are set in percentage by default so they are adaptive to the grid container.</li>
<li>We can create spacing between grid items using spacing</li>
<li><p>The grid container has five breakpoints and these breakpoints can be assigned to a value that represents how many of the 12 columns will be occupied by that item on that particular screen size.</p>
<p>Example: Implementing a simple responsive mui grid layout</p>
</li>
</ul>
<pre><code>   &lt;Grid container spacing={<span class="hljs-number">2</span>}&gt;
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">item</span> <span class="hljs-attr">xs</span>=<span class="hljs-string">{6}</span> <span class="hljs-attr">md</span>=<span class="hljs-string">{8}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>xs=6 md=8<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span></span>
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">item</span> <span class="hljs-attr">xs</span>=<span class="hljs-string">{6}</span> <span class="hljs-attr">md</span>=<span class="hljs-string">{4}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>xs=6 md=4<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span></span>
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">item</span> <span class="hljs-attr">xs</span>=<span class="hljs-string">{6}</span> <span class="hljs-attr">md</span>=<span class="hljs-string">{4}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>xs=6 md=4<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span></span>
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">item</span> <span class="hljs-attr">xs</span>=<span class="hljs-string">{6}</span> <span class="hljs-attr">md</span>=<span class="hljs-string">{8}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>xs=6 md=8<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span></span>
   &lt;/Grid&gt;
</code></pre><p>Output: </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667391964746/yInZDDvhI.avif" alt="NI-Ue3cxo (1).avif" />
for example here on the first item xs={6} md={8} sizes that grid item to occupy 8 columns when the viewport width is 900 or more pixels. For smaller viewports, the component fills half of the viewport width (6 columns).</p>
<h3 id="heading-auto-layout-grid-container">Auto Layout grid container</h3>
<p> we can also create items to take space dynamically according to the screen size, we can set the width of one item and the others will automatically resize around it.</p>
<pre><code>  &lt;Grid container spacing={<span class="hljs-number">3</span>}&gt;
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">item</span> <span class="hljs-attr">xs</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>xs<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span></span>
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">item</span> <span class="hljs-attr">xs</span>=<span class="hljs-string">{6}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>xs=6<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span></span>
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Grid</span> <span class="hljs-attr">item</span> <span class="hljs-attr">xs</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>xs<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Grid</span>&gt;</span></span>
  &lt;/Grid&gt;
</code></pre><p>Output :
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667391797453/T-DDPSq0Y.avif" alt="0OP4TkUgO.avif" /></p>
<h1 id="heading-2-textfield">2. Textfield</h1>
<p>The textfield component is a complete form control HTML input including a label, input, and helper text which can further be customized with wrapped icons inside too.
It comes with three variants outlined(default), standard, and filled. </p>
<pre><code>&lt;TextField id=<span class="hljs-string">"outlined-basic"</span> label=<span class="hljs-string">"Outlined"</span> variant=<span class="hljs-string">"outlined"</span> /&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TextField</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"filled-basic"</span> <span class="hljs-attr">label</span>=<span class="hljs-string">"Filled"</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"filled"</span> /&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TextField</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"standard-basic"</span> <span class="hljs-attr">label</span>=<span class="hljs-string">"Standard"</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"standard"</span> /&gt;</span></span>
</code></pre><p>Output: 
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667392855299/kiwjhrq99.png" alt="image.png" /></p>
<p>It supports form props such as required, disabled, type, etc. as well as helper text to display conditionally under the input label.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667393121866/HnoYF_d-Xz.png" alt="image.png" />
The error prop toggles the error state.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667393156574/WNZ7iIjSC.png" alt="image.png" />
We can further customize it using select prop and make it a downtown input too along with icons display.</p>
<h3 id="heading-input-adornments">Input adornments</h3>
<p>Input adornment can be used to add prefixes, suffixes, or on action icons or functionality to an input such as a button to hide or reveal passwords.</p>
<pre><code>  <span class="hljs-keyword">const</span> [showPassword, setShowPassword] = useState(<span class="hljs-literal">false</span>)

  <span class="hljs-keyword">const</span> handleClickShowPassword = <span class="hljs-function">() =&gt;</span> setShowPassword(!showPassword)

  &lt;OutlinedInput
        id=<span class="hljs-string">"outlined-adornment-password"</span>
        type={showPassword ? <span class="hljs-string">'text'</span> : <span class="hljs-string">'password'</span>}
        endAdornment={
          <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">InputAdornment</span> <span class="hljs-attr">position</span>=<span class="hljs-string">"end"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">IconButton</span>
              <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClickShowPassword}</span>
              <span class="hljs-attr">edge</span>=<span class="hljs-string">"end"</span>
            &gt;</span>
              {showPassword ? <span class="hljs-tag">&lt;<span class="hljs-name">VisibilityOff</span> /&gt;</span> : <span class="hljs-tag">&lt;<span class="hljs-name">Visibility</span> /&gt;</span>}
            <span class="hljs-tag">&lt;/<span class="hljs-name">IconButton</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">InputAdornment</span>&gt;</span></span>
        }
        label=<span class="hljs-string">"Password"</span>
  /&gt;
</code></pre><p>Output: 
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667395323829/K9I3ady57.gif" alt="ezgif-4-43b800d236.gif" /></p>
<h1 id="heading-3-image-list">3. Image List</h1>
<p>The image list component can be used when we wish to display a collection of images in an organized manner.
Mui provides different variants with the image list component to display images differently such as standard, quilted, woven, and masonry.
Mui also provides ImageListItemBar to add an overlay to each item. The overlay can accommodate a title, subtitle, and secondary action.</p>
<p>Masonry image list example : </p>
<pre><code>  &lt;ImageList cols={<span class="hljs-number">3</span>} gap={<span class="hljs-number">8</span>} variant=<span class="hljs-string">"masonry"</span>&gt;
          {itemData2.map(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> (
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ImageListItem</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.title}</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">img</span>
                <span class="hljs-attr">src</span>=<span class="hljs-string">{</span>`${<span class="hljs-attr">item.img</span>}?<span class="hljs-attr">w</span>=<span class="hljs-string">248&amp;fit</span>=<span class="hljs-string">crop&amp;auto</span>=<span class="hljs-string">format&amp;dpr</span>=<span class="hljs-string">2</span>`}
                <span class="hljs-attr">alt</span>=<span class="hljs-string">{item.title}</span>
                <span class="hljs-attr">loading</span>=<span class="hljs-string">"lazy"</span>
              /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ImageListItemBar</span> <span class="hljs-attr">title</span>=<span class="hljs-string">{item.title}</span> /&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">ImageListItem</span>&gt;</span></span>
          ))}
  &lt;/ImageList&gt;
</code></pre><p>output: 
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667404701119/lpSE_D0o0.png" alt="image.png" /></p>
<h1 id="heading-4-pagination">4. Pagination</h1>
<p>One of the most important things about making your website more user-friendly is reducing the response time. Rendering a huge data on page build will slow down the webpage a lot, therefore when you have a lot of elements on a page you can render them accordingly by separating them into pages and for that mui provides an amazing pagination component.</p>
<p>Material-UI provides a Pagination component that enables the user to select a specific page from a range of pages</p>
<pre><code>&lt;Stack spacing={<span class="hljs-number">2</span>}&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Pagination</span> <span class="hljs-attr">count</span>=<span class="hljs-string">{10}</span> /&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Pagination</span> <span class="hljs-attr">count</span>=<span class="hljs-string">{10}</span> <span class="hljs-attr">color</span>=<span class="hljs-string">"primary"</span> /&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Pagination</span> <span class="hljs-attr">count</span>=<span class="hljs-string">{10}</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"outlined"</span> /&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Pagination</span> <span class="hljs-attr">count</span>=<span class="hljs-string">{10}</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"outlined"</span> <span class="hljs-attr">color</span>=<span class="hljs-string">"primary"</span> /&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Pagination</span> <span class="hljs-attr">count</span>=<span class="hljs-string">{10}</span> <span class="hljs-attr">shape</span>=<span class="hljs-string">"rounded"</span> /&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Pagination</span> <span class="hljs-attr">count</span>=<span class="hljs-string">{10}</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"outlined"</span> <span class="hljs-attr">shape</span>=<span class="hljs-string">"rounded"</span> /&gt;</span></span>
&lt;/Stack&gt;
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667406683474/hYctAjeTp.png" alt="image.png" /></p>
<p>There are multiple variants available for the pagination component which can also be further customized as per your need.</p>
<h1 id="heading-5-skeleton">5. Skeleton</h1>
<p>A skeleton screen is a version of the UI that doesn’t contain actual content; instead, it mimics the page’s layout by showing its elements in a shape similar to the actual content as it is loading, this also helps the UI to not be disturbed by the absence of elements and their sudden load.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667405132840/GMLz0T8pB.png" alt="image.png" />
Material UI provides the skeleton component to create such a skeleton screen. It provides these variants along with the component.
text (default): represents a single line of text (you can adjust the height via font size).
circular, rectangular, and rounded: come with different border-radius to let you take control of the size.</p>
<pre><code><span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">true</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        setLoading(<span class="hljs-literal">false</span>)
    }, <span class="hljs-number">3000</span>)
  }, [])

&lt;Box sx={{ <span class="hljs-attr">width</span>: <span class="hljs-string">"250px"</span> }}&gt;
  {loading ? (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Skeleton</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">sx</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">fontSize:</span> '<span class="hljs-attr">1rem</span>' }} /&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Skeleton</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"circular"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">{40}</span> <span class="hljs-attr">height</span>=<span class="hljs-string">{40}</span> /&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Skeleton</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"rectangular"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">{210}</span> <span class="hljs-attr">height</span>=<span class="hljs-string">{60}</span> /&gt;</span></span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Skeleton</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"rounded"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">{210}</span> <span class="hljs-attr">height</span>=<span class="hljs-string">{60}</span> /&gt;</span></span>
    ) : (
          <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">img</span>
            <span class="hljs-attr">src</span>=<span class="hljs-string">"https://source.unsplash.com/random/256x144"</span>
            <span class="hljs-attr">alt</span>=<span class="hljs-string">"skeleton"</span>
            <span class="hljs-attr">width</span>=<span class="hljs-string">{256}</span>
            <span class="hljs-attr">height</span>=<span class="hljs-string">{144}</span>
          /&gt;</span></span>
 )}
</code></pre><p>Output:  (stays for 3 seconds and then displays the image)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667405822887/ZypZoB60F.png" alt="image.png" /></p>
<h1 id="heading-6-timeline">6. Timeline</h1>
<p>The timeline component can be used to display a list of events in chronological order.
There are different ways in which a Timeline can be placed, and customized.</p>
<pre><code>&lt;Timeline position=<span class="hljs-string">'alternate'</span>&gt;
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TimelineItem</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TimelineOppositeContent</span> <span class="hljs-attr">color</span>=<span class="hljs-string">'text.secondary'</span>&gt;</span>09:30 AM<span class="hljs-tag">&lt;/<span class="hljs-name">TimelineOppositeContent</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TimelineSeparator</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">TimelineDot</span> <span class="hljs-attr">color</span>=<span class="hljs-string">'info'</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">'outlined'</span>/&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">TimelineConnector</span>/&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">TimelineSeparator</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">TimelineContent</span>&gt;</span>City A<span class="hljs-tag">&lt;/<span class="hljs-name">TimelineContent</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">TimelineItem</span>&gt;</span></span>
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TimelineItem</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">TimelineOppositeContent</span> <span class="hljs-attr">color</span>=<span class="hljs-string">'text.secondary'</span>&gt;</span>10:00
AM<span class="hljs-tag">&lt;/<span class="hljs-name">TimelineOppositeContent</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TimelineSeparator</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">TimelineDot</span> <span class="hljs-attr">color</span>=<span class="hljs-string">'info'</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">'filled'</span>/&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">TimelineConnector</span>/&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">TimelineSeparator</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">TimelineContent</span>&gt;</span>City B<span class="hljs-tag">&lt;/<span class="hljs-name">TimelineContent</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">TimelineItem</span>&gt;</span></span>
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TimelineItem</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">TimelineOppositeContent</span> <span class="hljs-attr">color</span>=<span class="hljs-string">'text.secondary'</span>&gt;</span>10:30 AM<span class="hljs-tag">&lt;/<span class="hljs-name">TimelineOppositeContent</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TimelineSeparator</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">TimelineDot</span> <span class="hljs-attr">color</span>=<span class="hljs-string">'info'</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">'outlined'</span>/&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">TimelineSeparator</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">TimelineContent</span>&gt;</span>City C<span class="hljs-tag">&lt;/<span class="hljs-name">TimelineContent</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">TimelineItem</span>&gt;</span></span>
    &lt;/Timeline&gt;
</code></pre><p>Output: </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667408210925/1Nx2G3wKg.png" alt="image.png" /></p>
<h3 id="heading-other-honorable-mui-components">Other honorable mui components</h3>
<ul>
<li>Breadcrumbs</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667406881934/dZ9FP2UtI.png" alt="image.png" /></p>
<ul>
<li>Tabs</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667408439815/APO1P_FpQ.png" alt="image.png" /></p>
<ul>
<li>App bar</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667408542142/Dti7XQENM.png" alt="image.png" /></p>
<ul>
<li>Speed Dial</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667408019297/2DGG3kbsm.png" alt="image.png" /></p>
<ul>
<li>LoadingButton</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667408485811/2sgkEy-89.gif" alt="ezgif-1-cff92a9c1b (1).gif" /></p>
<p>That's all for now, more about these components is available on the official <a target="_blank" href="https://mui.com/material-ui/getting-started/overview/">mui website</a></p>
<p>Thank you for reading till the last.</p>
<p>Reach me on <a target="_blank" href="twitter.com/Aadarsh805">Twitter</a></p>
]]></content:encoded></item><item><title><![CDATA[React Context API. What is it and why is it important?]]></title><description><![CDATA[Why React Context?
If you have worked with react, you must have the idea of how data is passed in react.
React context helps to pass data without prop drilling. Let's first see what prop drilling is.
Prop Drilling

Passing data in react is straightfo...]]></description><link>https://aadarshthakur.hashnode.dev/react-context-api-what-is-it-and-why-is-it-important</link><guid isPermaLink="true">https://aadarshthakur.hashnode.dev/react-context-api-what-is-it-and-why-is-it-important</guid><category><![CDATA[React]]></category><dc:creator><![CDATA[Aadarsh Thakur]]></dc:creator><pubDate>Mon, 25 Jul 2022 17:30:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1658768604376/-bs3WV_bH.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-why-react-context">Why React Context?</h1>
<p>If you have worked with react, you must have the idea of how data is passed in react.
React context helps to pass data without prop drilling. Let's first see what prop drilling is.</p>
<h1 id="heading-prop-drilling">Prop Drilling</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658768623551/GBnM8_DjP.png" alt="Untitled (1).png" /></p>
<p>Passing data in react is straightforward. It is top to down, from parent to child component.
Prop drilling is accessing data from high-level components to the child components.
Why is this a problem?</p>
<p>Suppose you are working on a pretty large project having a quite big component tree and you want to pass down an authenticated user to a component down at the bottom of the tree. In such a situation you'll have to pass that user or props from all the components in between which might not even need access to that data or props. In such cases we can use react context api.
Now let's see how React context solves this problem.</p>
<h1 id="heading-how-does-context-solve-the-problem-of-prop-drilling">How does context solve the problem of prop drilling?</h1>
<p>In easy language, Context API is a way to make global variables or props.
It is basically used when some data needs to be accessible by many components at different nesting levels.</p>
<h1 id="heading-how-does-context-work">How does context work?</h1>
<p>For using this we have to create an object using React.createContext() globally.</p>
<pre><code>const MyContext <span class="hljs-operator">=</span> React.createContext(defaultValue);
</code></pre><p>the object comes with a provider component that assigns the value to the object.</p>
<pre><code>export const App <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  const [user, setUser] <span class="hljs-operator">=</span> useState(<span class="hljs-string">"Aadarsh"</span>);

  <span class="hljs-keyword">return</span> (
    <span class="hljs-operator">&lt;</span>MyContext.Provider value<span class="hljs-operator">=</span>{user}<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>h1<span class="hljs-operator">&gt;</span>{`Hello ${user}`}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>h1<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>ChildComponent user<span class="hljs-operator">=</span>{user} <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>MyContext.Provider&gt;
  );
}
</code></pre><p>Now all the components in the component tree will have direct access to the user. </p>
<p>To access this data to the final component we use useContext()</p>
<pre><code>const <span class="hljs-keyword">user</span> = useContext(MyContext)
</code></pre><h1 id="heading-where-to-use-context">Where to Use context?</h1>
<p>Wherever some data needs to be passed deep down in the component tree, it's better to use context</p>
<ul>
<li><p>Passing user data from login form to cart checkout</p>
</li>
<li><p>Building a theme-toggler component that toggles between light and dark mode and every component needs access to it to be styled accordingly.</p>
</li>
</ul>
<p>That's all for now, read more about React context here <a target="_blank" href="Link"><a target="_blank" href="https://reactjs.org/docs/context.html">reactjs.org/docs/context.html</a></a></p>
<p>Thank you for reading till the last. </p>
<p>Reach me on <a target="_blank" href="https://twitter.com/Aadarsh805">Twitter</a></p>
]]></content:encoded></item><item><title><![CDATA[Getting started with frontend web development]]></title><description><![CDATA[1.  Getting started with Computer Science fundaments

Before getting started with any development field, one must have basic CS fundamentals knowledge, and there is no other better course than Harvard's CS50 course
2. Learn Data Structures and Algori...]]></description><link>https://aadarshthakur.hashnode.dev/getting-started-with-frontend-web-development</link><guid isPermaLink="true">https://aadarshthakur.hashnode.dev/getting-started-with-frontend-web-development</guid><category><![CDATA[Frontend Development]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Aadarsh Thakur]]></dc:creator><pubDate>Mon, 04 Jul 2022 13:55:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1656942734555/tqtPJ-uPL.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-1-getting-started-with-computer-science-fundaments">1.  Getting started with Computer Science fundaments</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1656941279114/iK4lJ8MN_.jpg" alt="maxresdefault (1).jpg" />
Before getting started with any development field, one must have basic CS fundamentals knowledge, and there is no other better course than <a target="_blank" href="https://cs50.harvard.edu/x/2022/weeks/">Harvard's CS50 course</a></p>
<h1 id="heading-2-learn-data-structures-and-algorithms-dsa">2. Learn Data Structures and Algorithms (DSA)</h1>
<p>DSA is the building block of the software development process. It is not limited to a single programming language.
It is said DSA is a must to crack any computer science job interview and it's changing nowadays a little but still being good at DSA has a lot of advantages 
practicing and solving DSA questions help you build logic faster. DSA actually trains you to think in different ways. And there are many many advantages of doing DSA.
There are a bunch of free awesome courses on DSA on Udemy and YouTube and a bunch of websites like Leetcode etc. to practice DSA questions.</p>
<h1 id="heading-3-learn-html-and-css">3. Learn HTML and CSS</h1>
<p>HTML is the building block of a webpage and CSS is also as much as important as HTML on a webpage. CSS is used to style and rearrange your HTML file as per desired and also used to make web pages responsive.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1656941896187/9-cvXgcm9.jpg" alt="html-css-code-developing-screenshot-76836093.jpg" /></p>
<h1 id="heading-4-learn-javascript">4. Learn Javascript</h1>
<p>For adding user interactivity to your web page, javascript is used. Learning JS in 2022 is the best investment you can do on yourself. It is highly used programming language in different fields.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1656942093644/9fGG7TlOI.png" alt="6288755792019456.png" /></p>
<h1 id="heading-5-learn-git-and-github">5. Learn Git and Github</h1>
<p>Git is a free and open source version control system. It is used for tracking changes in any set of files, usually used for coordinating work among programmers collaboratively. 
GitHub is a provider of Internet hosting for software development and version control using Git. It offers the distributed version control and source code management functionality of Git. 
Git and GitHub are a must-have tech skill. </p>
<h1 id="heading-6-develop-a-portfolio-website-to-list-all-your-projects">6. Develop a portfolio website to list all your projects</h1>
<p>Now that you have come this far, you should have good enough skill to create your own portfolio website, where you can showcase your skills and projects and every information about you.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1656942374752/ocFZDCR-3.png" alt="a1614500-e03f-11eb-986a-30f6f0d4f1cc.png" /></p>
<h1 id="heading-7-learn-react">7. Learn React</h1>
<p>React is a open source Javascript library developed by Facebook. React helps create faster and flexible webpages using webpacks and is one of most propular JS library. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1656942639848/EKx4CE2d7.webp" alt="s1i3j6powyg7tclhwj5x.webp" /></p>
<p>That's all for now.# 
Follow me on Twitter: https://twitter.com/Aadarsh805
Linkedin: https://www.linkedin.com/in/aadarsh-thakur-090a31227/</p>
]]></content:encoded></item></channel></rss>