<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hossein Ahmadi on Medium]]></title>
        <description><![CDATA[Stories by Hossein Ahmadi on Medium]]></description>
        <link>https://medium.com/@hosseinamd?source=rss-ee208eb13e4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AFuOqdyCdoc67fxb_7oa6A.png</url>
            <title>Stories by Hossein Ahmadi on Medium</title>
            <link>https://medium.com/@hosseinamd?source=rss-ee208eb13e4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 21:42:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hosseinamd/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Build a React App with RTK-QUERY]]></title>
            <link>https://javascript.plainenglish.io/how-to-build-a-react-app-with-rtk-query-110cb611e8fc?source=rss-ee208eb13e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/110cb611e8fc</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hossein Ahmadi]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 16:16:39 GMT</pubDate>
            <atom:updated>2023-03-07T16:16:39.662Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhance your service layer in your redux-toolkit projects</h4><h4>A beginners’ guide to writing queries with rtk-query</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gbDzy1boy32jRWti" /><figcaption>Photo by <a href="https://unsplash.com/@f12r?utm_source=medium&amp;utm_medium=referral">Fahim Muntashir</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is impossible to be a Front end developer working with React and not heard about redux in your life. Most companies are using redux in their codebase and knowing the basic concepts of it has become one of the essences of being a Frontender. There are a lot of discussions about using or not using it in your product. The truth is, you never can find a perfect tool for all projects. You should decide which tools are the best fit for your objectives and product. Although there are some pros and cons for each tool, the most important thing is the trade-off between the benefits and downsides of the tool for <strong>YOU</strong>.</p><blockquote><strong>RTK Query</strong> is a powerful data fetching and caching tool. It is designed to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching &amp; caching logic yourself.</blockquote><p>If you are using redux, especially <a href="https://redux-toolkit.js.org/">redux-toolkit</a>, you already know that <a href="https://redux-toolkit.js.org/rtk-query/overview">rtk-query</a> comes as a built-in dependency with it. There are a lot of similar tools like react-query out there, but when you are using redux-toolkit, and already have rtk-query in your bundle, why not use it? Some benefits of trk-query are:</p><ul><li>It’s completely compatible with redux</li><li>Written in TypeScript</li><li>Improves your service layer to be more reusable and gets your project with auto-generated hooks to the next level</li><li>It’s trackable and observable through <em>redux-devtools</em></li><li>It has a really nice caching behavior</li></ul><p>In this article, I will help you to build a simple blog React application with rtk-query and typescript to get you more familiar with this great tool. This application consists of a view to show a list of posts and a simple form to add a post.</p><h4>Prerequisite</h4><ol><li>You should know <strong>React</strong></li><li>You should know <strong>redux</strong> and <strong>redux-toolkit</strong> concepts and want to use them in your project</li><li>Having experience with <strong>TypeScript</strong> is a plus, but you can just remove TS parts from the codes and it works with JavaScript for you :)</li></ol><blockquote>You can find the repository and all the codes I mention in this article <a href="https://github.com/hosseinAMD/rtk-query-playground">here</a>. Live version of the final project can be found <a href="https://hosseinamd.github.io/rtk-query-playground/">here</a>. I also skip style or simple JSX parts explanations since the main topic here is rtk-query.</blockquote><h3>How does it work?</h3><p>As I mentioned earlier, rtk-query is a fetching tool that provides tons of features to make your project more cleaner and reusable. Your services can be created in the shape of endpoints and queries by using <em>createApi</em> which is completely similar to <em>createReducer</em>. It generates hooks for your queries and you can use them easily in your components. You won’t need loading states, error handling, refetch functions, prefetch with useEffect, and data parsers anymore because rtk-query will take care of that for you.</p><p>In fact, queries are the smallest pieces of your services which can be GET or POST to get or send data to the server. All the queries related to an entity are packed in one endpoint that is created by <em>createApi</em>. In the end, your service layer is a combination of different endpoints including their own queries.</p><p>rtk-query is using fetch API from JavaScript. But you can configure it to use <a href="https://axios-http.com/docs/intro">axios</a> or graphql. Also, it wraps your queries by <a href="https://immerjs.github.io/immer/">immer</a> so mutating data is not a concern anymore.</p><figure><img alt="Services and components layer" src="https://cdn-images-1.medium.com/max/581/1*8AaAjpOcFZMmU7WOAqz58A.png" /><figcaption>Services and components layer graph</figcaption></figure><h3>Building the foundations</h3><p>You can choose <strong>ANY</strong> tools and setup you like for this project. I will use Vite, but it doesn’t matter if you like CRA more or you prefer to config your own boilerplate. After creating our React project, we should install redux-toolkit + axios and configure it:</p><pre>npm install @reduxjs/toolkit react-redux axios</pre><p>First, we should create our base query function to configure rtk-query to use axios:</p><pre>// src/services/api.ts<br><br>const axiosBaseQuery =<br>  (): BaseQueryFn&lt;AxiosRequestConfig, unknown, AxiosError&gt; =&gt;<br>  async ({ url, method, data, params }) =&gt; {<br>    try {<br>      Axios.defaults.baseURL = &quot;https://jsonplaceholder.typicode.com/&quot;;<br>      const result = await Axios({<br>        url,<br>        method,<br>        data,<br>        params,<br>      });<br>      return { data: result.data };<br>    } catch (axiosError) {<br>      const error = axiosError as AxiosError;<br>      return {<br>        error,<br>      };<br>    }<br>  };</pre><p><em>BaseQueryFn</em> is a promise that should resolve our request with some data or reject it with an error object. Here, we receive axios simple request configs from our queries and perform the API fetching with axios. Then we will return data if everything was fine. Otherwise, we reject it with the error object. <strong>Make sure to return data or errors in an object, otherwise, rtk-query doesn’t understand it.</strong></p><blockquote>We will use <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a> free APIs in this project.</blockquote><p>Second, we should tell rtk-query, to use our custom query function instead of JS fetch API. It’s simply doable by passing our function to <em>createApi</em>.</p><pre>// src/services/api.ts<br><br>export const apiService = createApi({<br>  baseQuery: axiosBaseQuery(),<br>  endpoints: () =&gt; ({}),<br>});</pre><p>Now, we can simply add our queries to the endpoints. But as you can see, we returned an empty object. The reason is that in the real world, we don’t want to have all of our services in a single long-messy file. We want to split them into multiple small modules to have a cleaner codebase. So, we return an empty object and simply <strong>inject</strong> our endpoints into this object later.</p><p>Finally, we need to add <em>apiService</em> to redux store and add the store to our app:</p><pre>// src/store/store.ts<br><br>export const store = configureStore({<br>  reducer: {<br>    [apiService.reducerPath]: apiService.reducer,<br>  },<br>  middleware: (getDefaultMiddleware) =&gt;<br>    getDefaultMiddleware().concat(apiService.middleware),<br>});</pre><pre>// src/main.tsx <br><br>&lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br> &lt;/Provider&gt;</pre><blockquote><strong>Why? </strong>apiService also contains an auto-generated Redux slice reducer and a custom middleware that manages subscription lifetimes. Both of those need to be added to the Redux store</blockquote><h3>Building our first service</h3><p>We start with <em>GET</em> endpoint to retrieve the list of posts from the server. We can simply use <em>injectEndpoint</em> API from rtk-query, to create our endpoints and add them to our base service layer.</p><pre>// src/services/posts.ts<br><br>// Interface of JSONPlaceholder posts<br>export interface Post {<br>  id: number;<br>  userId: number;<br>  title: string;<br>  body: string;<br>}<br><br>export const postService = apiService.injectEndpoints({<br>  endpoints: (build) =&gt; ({<br>    // query&lt;ResultType, QueryArg&gt;<br>    getPosts: build.query&lt;Post[], null&gt;({<br>      query: () =&gt; ({ method: &quot;GET&quot;, url: &quot;posts&quot; }),<br>    }),<br>  }),<br>});<br><br>// Auto-generated hooks<br>export const { useGetPostsQuery } = postService;</pre><p><em>endpoints</em> is a function with one mandatory argument — build — which returns an object of different queries. build is a utility that helps you to create your endpoints by using different constructors.<em> build.query</em> should be used for <em>GET</em> endpoints and <em>build.mutation</em> should be used for other endpoints like <em>POST</em> and <em>PATCH</em>. It’s a little bit similar to what we have in graphql. These constructors receive an object that has one mandatory argument which is <em>query</em>. <em>query</em> in simple words is the function that you use to fetch API and should return your axios request configs like method, params, and url.</p><p>Then, rtk-query creates hooks for you to fetch these queries easily. You can pass more settings to your query constructors like <em>transformResponse</em> which we don’t cover because they are out of this article&#39;s scope.</p><h3>Let’s use our first service</h3><p>Now it’s time to use our service. rtk-query generated <em>useGetPostsQuery</em> hook for us. This hook returns an object consisting of some useful values to use. Like loading state, error, returned data, and refetch function.</p><ul><li><strong>Loading state:</strong> It will be <em>true</em> when we execute this query in our component.</li><li><strong>Error object:</strong> If our query fails, an error object will be returned, Otherwise it’s <em>null</em>.</li><li><strong>data: </strong>Our returned data. It’s <em>null</em> until our query executes <strong>successfully</strong>.</li><li><strong>refetch function: </strong>We can use this function to re-run the query whenever we need. For example, in case we want to have a “Try again” or refresh button.</li></ul><pre>// src/components/PostList.tsx<br><br>const PostList: React.FC&lt;unknown&gt; = () =&gt; {<br>  const { data: posts, isLoading, error, refetch } = useGetPostsQuery(null);<br><br>  if (isLoading) {<br>    return &lt;div&gt;Loading posts...&lt;/div&gt;;<br>  }<br><br>  if (error) {<br>    return &lt;ErrorBanner error={error as AxiosError} refetch={refetch} /&gt;;<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Posts&lt;/h2&gt;<br>      &lt;div&gt;<br>        {posts?.map((post) =&gt; (<br>          &lt;div className=&quot;postItem&quot;&gt;<br>            &lt;h4&gt;{post.title}&lt;/h4&gt;<br>            &lt;p&gt;{post.body}&lt;/p&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default PostList;</pre><p><em>useQuery</em> hook fetches our API on the component mount for the first time. We can manually control it by using useLazyQuery instead. As you can see, our component is much cleaner now and we haven’t used any <em>useEffect</em> or <em>useState</em> in our component.</p><figure><img alt="Posts list" src="https://cdn-images-1.medium.com/max/848/1*2jUzgyNpP_IsoDXFGU2jIQ.png" /><figcaption>Posts list</figcaption></figure><h3>Let’s build our form</h3><p>To move further, let’s cover one mutation query also. We want to create a post using a form that gets a title and body from users. Let’s start with the query itself:</p><pre>// src/services/posts.ts<br><br>export interface CreatePostDto {<br>  title: string;<br>  body: string;<br>}<br><br>export const postService = apiService.injectEndpoints({<br>  endpoints: (build) =&gt; ({<br>    // query&lt;ResultType, QueryArg&gt;<br>    getPosts: build.query&lt;Post[], null&gt;({<br>      query: () =&gt; ({ method: &quot;GET&quot;, url: &quot;posts&quot; }),<br>    }),<br>    // We use mutation for POST endpoints<br>    createPost: build.mutation&lt;Post, CreatePostDto&gt;({<br>      query: (data) =&gt; ({<br>        method: &quot;POST&quot;,<br>        url: &quot;posts&quot;,<br>        // We pass static userId to simplify this part<br>        data: { userId: 1, ...data },<br>      }),<br>    }),<br>  }),<br>});<br><br>// Auto-generated hooks<br>export const { useGetPostsQuery, useCreatePostMutation } = postService;</pre><p>Compared to <em>GET</em> endpoint, we have 2 differences here:</p><ol><li>Since we want to add some data with <em>POST</em> method, we use <strong><em>build.mutation</em></strong> instead of <em>build.query</em>.</li><li>We specified a new interface for the arguments of our endpoint and passed corresponding data to our axios request.</li></ol><p>Now we should use this new service in our form component:</p><pre>// src/components/PostForm.tsx<br><br>const PostForm: React.FC&lt;unknown&gt; = () =&gt; {<br>  const [title, setTitle] = useState&lt;string&gt;(&quot;&quot;);<br>  const [body, setBody] = useState&lt;string&gt;(&quot;&quot;);<br><br>  const [createPost, { isLoading }] = useCreatePostMutation();<br><br>  const submitForm = async (e: FormEvent) =&gt; {<br>    e.preventDefault();<br>    try {<br>      await createPost({ title, body });<br>    } catch (e) {<br>      console.log(e);<br>    }<br>  };<br><br>  return (<br>    &lt;form onSubmit={submitForm}&gt;<br>      &lt;input<br>        name=&quot;title&quot;<br>        type=&quot;text&quot;<br>        placeholder=&quot;Title&quot;<br>        value={title}<br>        onChange={(e) =&gt; setTitle(e.currentTarget.value)}<br>      /&gt;<br>      &lt;textarea<br>        name=&quot;body&quot;<br>        placeholder=&quot;Body...&quot;<br>        rows={5}<br>        value={body}<br>        onChange={(e) =&gt; setBody(e.currentTarget.value)}<br>      /&gt;<br>      &lt;input<br>        type=&quot;submit&quot;<br>        value={isLoading ? &quot;Wait...&quot; : &quot;Submit&quot;}<br>        disabled={isLoading}<br>      /&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default PostForm;</pre><p><em>useMutation</em> hook returns a tuple. The first item of this array is fetch API which you can call with specified arguments. The second item is an object that consists of some important values like loading state. It also returns an error object that we can use to show error in case of submitting data fails.</p><h3>Wrap it up</h3><p>We have covered the most important basic concepts of rtk-query. We saw how can we create our services and endpoints in a modular way and how to use fantastic auto-generated hooks in our components. Later on, I will publish follow-up articles explaining more advanced features and concepts of rtk-query like <strong>caching</strong>, <strong>fetching configuration</strong>, <strong>data transforming, etc .</strong></p><p>The full codebase of everything we have covered is published in this <a href="https://github.com/hosseinAMD/rtk-query-playground">repository</a> and deployed on this <a href="https://hosseinamd.github.io/rtk-query-playground/">page</a>.</p><p>If you have any recommendations or suggestions, feel free to ask me by my <a href="/service/mailto:hosseinamd96@gmail.com">private mail</a> or add comments and if you liked this article, <strong>don’t forget to clap!</strong></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=110cb611e8fc" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-build-a-react-app-with-rtk-query-110cb611e8fc">How to Build a React App with RTK-QUERY</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical interviews As a Frontend Engineer]]></title>
            <link>https://javascript.plainenglish.io/technical-interviews-as-a-frontend-engineer-364b7c78516?source=rss-ee208eb13e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/364b7c78516</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Hossein Ahmadi]]></dc:creator>
            <pubDate>Tue, 31 May 2022 08:18:03 GMT</pubDate>
            <atom:updated>2022-05-31T08:18:03.606Z</atom:updated>
            <content:encoded><![CDATA[<h4>Be informed about the road in front of you to get to your dream job.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PdfRktJSd0OnlIDa" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Finding a new job can be exciting and frustrating at once. After lots of research and reading about different companies, finally, you find a role that fits you and your skills. But, applying for it is just the start. You have to participate in an interview process and go over multiple steps to prove yourself as a future employee to the company. The number of steps can differ depending on the department and the role you are applying for, but if you are not prepared for interviews, you might lose the chance to get hired.</p><p>In this article, we will go over the usual steps that you have to take to get hired as a Front End Engineer. Of course, there is not just one way to hire people, nor a recipe for candidates to pass the interviews. Since not everyone will be the right candidate for every company and the other way around, the most important thing is to be ready to be your best self during the interviews. If you have information about the road in front of you, you will have a great chance to convince the employer you are the candidate they are looking for. In this particular article, we will focus on the engineering part of the process.</p><h3>Domain knowledge</h3><p>Usually, the first step of the engineering process would be an interview to understand your knowledge in the specific domains of the role. Nowadays, almost all Front End Engineers should have enough knowledge about JavaScript (or TypeScript). The purpose of this interview is to deep dive into how fluent you are in JS. You might be asked to describe some concepts, implement different functions and algorithms, calculate the output of a piece of code or even do some pair programming.</p><p>Usually, the interviewer will go over different aspects of the domain by asking questions with different levels of complexity.</p><blockquote><strong>Tip:</strong> Do not be afraid to ask questions or think loudly because you can prove to the person in front of you that even if you can not solve the problem, you have some good pieces of information about the concepts (Do not overuse it).</blockquote><h3>Coding Challenge</h3><p>Nothing can expose your Front End abilities better than <strong>code</strong>. There are lots of concepts and skills that can not be asked during interviews. So, a lot of companies opt to ask you to do a task to show your skills. The company will provide the task and ask you to do it at home or in some cases the company may invite you to the office. In this step, you are just simulating the way of doing tasks at the company and usually, you have a fixed or flexible time depending on the task.</p><p><strong>Pro Tips:</strong></p><p>Try to do your best and show what you can do as a Front End Engineer. Read about the requirements and “Plus Features” of the challenge and deliver the task with the highest possible quality. Write clean codes, pay attention to best practices and maybe try to use “Plus features” to show you are the best person for the job and take care of details and bugs. If you are asked to use a specific tool for some parts, do not replace it with another one. Do what you have been asked and do it in the right way!</p><p>Your code should be self-speaking, how you can ensure this? Providing good documentation, explaining your solutions, and having great structures are the most important factors in passing this step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d8rR2HzG2UjUObDy" /><figcaption>Photo by <a href="https://unsplash.com/es/@lukepeters?utm_source=medium&amp;utm_medium=referral">Luke Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Code review and specialized session</h3><p>If your task was what the company expected you will be invited to this step. Probably this is one of the most important and challenging parts of the hiring process. First, you are going to be asked to explain some parts of your code and discuss with the interviewer about other possible solutions. You do not have to accept everything, if you think something they are pointing out is wrong, don’t be afraid to speak up. Keep in mind that sometimes giving you wrong solutions or answers could be part of the process to understand if you can identify it and evaluate your ability to choose the right direction.</p><p>Furthermore, you will face some more specialized questions regarding the role you are applying for. You may also be asked to dive deep into different concepts of JS or UI libraries with your future colleagues and leaders to evaluate your abilities as an Engineer. Prepare yourself to speak and define easy and hard concepts and describe your experiences. This is the best step to show your knowledge and also to ask questions about your future role and tasks in the company.</p><h3>Product knowledge</h3><p>One of the biggest mistakes during the hiring process is to underestimate this step. You’re probably going to speak with Product Managers or Technical leads from the company to show how much you know about your future job. Honestly, You can not work on a product that you do not like with good performance. So, it is very important to know the product, technical stack, and tools of your future company as much as possible.</p><p>This step is the best place to ask questions about the development flow, technical challenges, different aspects of the product, and the plans of the company to expand it. Long story short, you have to make sure that you know the company and the product at the end of this session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YFo0UAel092coFoR" /><figcaption>Photo by <a href="https://unsplash.com/@linkedinsalesnavigator?utm_source=medium&amp;utm_medium=referral">LinkedIn Sales Solutions</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Have in mind to…</h3><ol><li>In all the steps, be kind, polite, and friendly. We are human after all.</li><li>Try to discuss respectfully when your opinion about some concept is not the same as the interviewer&#39;s. You should not accept everything without reason.</li><li>Ask questions even if you think they are stupid. Do not be afraid to know your future job better.</li><li>If you feel sick or stressed before the session, check if it is possible to change the time. You must be well prepared mentally for the interviews and everybody understands it.</li><li>Be on time and wear good clothes even if the interview is online.</li><li>Answer with <strong>“I don’t know”</strong> when you do not know! Nothing is worse than trying to make up stories when you do not have any idea about the questions.</li><li>Do not get stressed when you can not answer a question. Learn about it and show your passion for learning because it has a really good effect on the interviewer.</li><li>Ask about the feedback at the end of every meeting. Usually, interviewers provide some feedback if they will be allowed. Getting comments and feedback helps you to improve your personality and abilities.</li></ol><h3>Wrap up</h3><p>This article is not a secret weapon that will ensure you get every single job you’ve to do a process for. Take it as a guide with some common information on your way to getting your future job. The structure of the hiring process might be different between companies or even teams but the most important parts of them have been covered here. If you get rejected in some process, do not be disappointed or get stressed! It means you and the company are not a match and getting hired is going to make your life harder. Just be patient and you will find your dream job as soon as possible. Always be prepared and Good luck!</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Check out our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Community Discord</em></strong></a><em> and join our </em><a href="https://inplainenglish.pallet.com/talent/welcome"><strong><em>Talent Collective</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=364b7c78516" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/technical-interviews-as-a-frontend-engineer-364b7c78516">Technical interviews As a Frontend Engineer</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js Tutorial : Static and Dynamic Routing]]></title>
            <link>https://codeburst.io/next-js-tutorial-static-and-dynamic-routing-fba70e26359a?source=rss-ee208eb13e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fba70e26359a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-ssr]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <dc:creator><![CDATA[Hossein Ahmadi]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 00:04:41 GMT</pubDate>
            <atom:updated>2020-08-05T00:04:41.650Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to implement and use routes in Next.js</h4><h3>Next.js Tutorial : Static and Dynamic Routing</h3><h4>Why you should use Next.js and the basic concepts of routing</h4><p>Hello everyone! Around one month ago I wanted to start building SSR and SEO Friendly Websites using React and started looking for a nice tutorial for <strong>Next.js — One of the best available tools —</strong> of this purpose. But I couldn’t find one. So I decided to create one of my own, which turned into this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iQn2GLCJi5CSDLKq" /><figcaption>Photo by <a href="https://unsplash.com/@i_m_noble?utm_source=medium&amp;utm_medium=referral">Ian Noble</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why SSR?</h3><p>I don’t want to dive deep into the basic comparisons of SSR and CSR but in summary, we’re covering some different and concepts of SSR web applications.</p><p><strong>SSR </strong>— server-side rendering — and <strong>CSR </strong>— client-side rendering — are both types of rendering your pages for your clients and customers. In CSR, the server sends a <strong>blank </strong>HTML file to the client and the responsibility of filling it with JS files is on the client’s browser’s shoulders. When you create a React application with CRA, or your boilerplate and deploy it on the server, you create a CSR web application! So, if you open your page source in the browser, you find your div with root id <strong>EMPTY</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FX_IZXuJWjtneDs0XU9x1w.jpeg" /><figcaption>Empty page source in CSR web applications</figcaption></figure><p>But in SSR web applications, you will render your HTML file on your server, then send it to the client browser. This approach has two benefits:</p><p>1. Faster page loading and better experience for clients (The horrible blank loading page!). It’s faster because your servers are a lot more powerful than most of your clients!</p><p>2. It’s SEO friendly and google crawlers have everything in Page Source.</p><p>You can read about CSR and SSR in the great article of Alex Grigoryan here in <a href="https://medium.com/walmartlabs/the-benefits-of-server-side-rendering-over-client-side-rendering-5d07ff2cefe8#:~:text=The%20main%20difference%20is%20that,with%20links%20to%20your%20javascript.">The Benefits of Server Side Rendering Over Client Side Rendering!</a></p><h3>Why Next.js?</h3><p>Honestly, you can create your SSR React Web Application without using any framework or tools. But it’s so hard and complex and you have to spend a lot of time to fix its bugs! There are some tools that can help you to overcome mentioned challenges like Razzle, After JS, Next JS, and Gatsby. But the most powerful and featured framework is Next.js!</p><p>Here are some of Next.js’s benefits:</p><p><strong>1. Zero Config:</strong> Like CRA, you can use Next easily without diving into webpack and babel configurations.</p><p><strong>2. Built-in CSS libraries:</strong> So you want to use CSS-in-JS or SCSS? Don’t worry! Next provides them for you.</p><p><strong>3. Powerful in pre-rendering.</strong></p><p><strong>4. Easy and simple configuration</strong></p><p><strong>5. Hot reloading:</strong> Develop, save, and see your changes instantly!</p><p>So, why recreate the wheel? Let’s start using Next.js!</p><h3>Prerequisites</h3><p>If you want to understand everything in this article (and the next articles), you should have a good understanding and experience in <strong>React</strong>. Obviously, you should have a great understanding of<strong> JavaScript, HTML, and CSS too</strong>. I’m using functional programming and it’ll be good if you will be familiar with functional components and <strong>React Hooks</strong>. You can read about hooks in my 2 articles:</p><p><a href="https://medium.com/weekly-webtips/react-hooks-for-beginners-sweet-and-a-little-complex-31a1225bd2f7">React Hooks for beginners, Sweet and a little complex</a></p><p><a href="https://medium.com/javascript-in-plain-english/react-hooks-how-to-use-useeffect-ecea3e90d84f">React Hooks: How to use useEffect()</a></p><p>And you should have Nodejs and Node package manager or yarn installed on your machine.</p><p>Repo Link: <a href="https://github.com/hosseinAMD/next-playground">https://github.com/hosseinAMD/next-playground</a></p><h3>Creating our Next.js project</h3><p>Like CRA, you have a very simple way to create your application with Next.js. open your bash and type this command:</p><pre>npx create-next-app [your-project-name]</pre><p>or</p><pre>yarn create next-app [your-project-name]</pre><p>At the beginning of the installation, you will be asked to choose a template and you can choose the basic starter template.</p><p>Finally, you can run your project in development mode by typing in your project directory:</p><pre>yarn dev</pre><pre>npm run dev</pre><h3>Static Routing</h3><p>Routing system in Next.js is different from what you have been used to in React by react-router. Routing is <strong>directory-based</strong> and there is no need to type any code to create your routes. If you look up in your project root, you can find a folder named <strong>“pages”</strong>. The routing of your application is completely related to this folder and files inside it.</p><p>The <strong>“index.js”</strong> file in this folder is your “/” route. So, if you open your browser and type <a href="http://localhost:3000/">http://localhost:3000</a> you will see the index.js contents. Consider that we want to create a <strong>“/about”</strong> route in our application. Simply create a new file in <strong>“pages” </strong>directory named “about” and create a functional component like this in it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de0200898e989d8e06b7773346ac793b/href">https://medium.com/media/de0200898e989d8e06b7773346ac793b/href</a></iframe><blockquote>Tip: There is no need to import React. Next.js will import it for you!</blockquote><p>And now open <a href="http://localhost:3000/about">http://localhost:3000/about</a> in your browser and you can see your about page rendering nice and our routing works perfectly. If you want to create a route like <strong>“/contact/map” </strong>for example, you can easily create a directory named “contact” and then a <strong>“map.js”</strong> file!</p><h3>Navigating between routes</h3><p>In Next.js we don’t have any NavLink components to navigate between our routes. And we should not use &lt;a&gt; tag because this will refresh your page completely and you can’t use high performance or the benefits of React’s Virtual DOM! So how do we navigate between our routes in a smooth and modern way?</p><p>Next.js has a nice API called <strong>“next/link”</strong> which you can import <strong>“Link”</strong> from this API and wrap everything you want with it to act as a link for you. First, you should import Link and then wrap your &lt;a&gt; tag with it. Required property of this component is “href”. Let’s create a link to our about page in index.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7151a4f6c50409c3ad2cc8b0bab18f0f/href">https://medium.com/media/7151a4f6c50409c3ad2cc8b0bab18f0f/href</a></iframe><p>And if we test it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*i6aruv-Fsm82cuVuFh83Fw.gif" /></figure><p>Awesome! We created some routes and navigated between them perfectly!</p><h3>Dynamic Routing</h3><p>But what if you have an array of cities and you want to show a description for every city in your app? How do we implement a dynamic routing in our Next.js application? Dynamic routing in Next is very simple too! If you wrap your file name with <strong>[ ]</strong>, its behavior will be like <strong>“:var”</strong> in react-router. For example, if you create a directory named <strong>“cities”</strong> and inside it create a file named <strong>“[city].js”</strong>, you can type anything instead of city in your route and your [city].js component will be shown.This approach works for folders too.</p><p>Let’s test it. Consider we have an array of country and cities in our index.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bfc652c3773ac68a2d5dad4439baf44/href">https://medium.com/media/5bfc652c3773ac68a2d5dad4439baf44/href</a></iframe><p>We want to show a simple sentence like <strong>“City is placed in Country”</strong> when we click on every city. Create a directory named <strong>“[country]”</strong> and a file <strong>“[city].js” </strong>inside it. Our city component can be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/289b9c4f16893f0ddee6203ae90f1798/href">https://medium.com/media/289b9c4f16893f0ddee6203ae90f1798/href</a></iframe><p>We can access the values of our query parameters in our route by useRouter hook, imported from <strong>“next/router”</strong>. useRouter returns an object of your current route in the location bar and you can access its variables easily!</p><p>Now we should change our index.js to be able to navigate to our dynamic route:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51b2cad85468677038a6e3a50fcc91e8/href">https://medium.com/media/51b2cad85468677038a6e3a50fcc91e8/href</a></iframe><p>Awesome! But if you open your developer tools and look into your inspect tab, you see that all of the codes are changing. This is the bad behavior of &lt;a&gt; tag! To avoid this happening in dynamic routing you should pass your route template in <strong>“href”</strong> property, and the exact route in <strong>“as”</strong> property. So, change your index.js file like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9badc9f32177686fd83cebb44815556f/href">https://medium.com/media/9badc9f32177686fd83cebb44815556f/href</a></iframe><p>Let’s test it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DIDCEolXpy4lbeEoCDtz0Q.gif" /><figcaption>Dynamic navigating with correct behavior</figcaption></figure><p>Awesome! Everything is working great.</p><blockquote>Tip: you can create an “index.js” file in your directories so you will have your nested routes root page too. For example you can create “index.js” in your [country] folder so the <a href="http://localhost:3000/italy">http://localhost:3000/italy</a> is a valid route too and renders your “index.js” file’s content.</blockquote><h3>Final Words</h3><p>We successfully implemented static and dynamic routing in our first Next.js application. The routing system is the first and most important concept of Next applications.</p><p>In the following articles we will dive into more complex concepts of Next.js. Feel free to contact me at <a href="/service/mailto:hossein.ahmadi98@outlook.com"><strong>“hossein.ahmadi98@outlook.com”</strong> </a>or contribute to our playground repository!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fba70e26359a" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/next-js-tutorial-static-and-dynamic-routing-fba70e26359a">Next.js Tutorial : Static and Dynamic Routing</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use React Context — Part 1]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://codeburst.io/how-to-use-react-context-part-1-1e4ce38fe2dd?source=rss-ee208eb13e4d------2"><img src="https://cdn-images-1.medium.com/max/2600/0*D2WJG7Tey3vKSPh5" width="6000"></a></p><p class="medium-feed-snippet">React Context toturial in a project easy and simple!</p><p class="medium-feed-link"><a href="https://codeburst.io/how-to-use-react-context-part-1-1e4ce38fe2dd?source=rss-ee208eb13e4d------2">Continue reading on codeburst »</a></p></div>]]></description>
            <link>https://codeburst.io/how-to-use-react-context-part-1-1e4ce38fe2dd?source=rss-ee208eb13e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e4ce38fe2dd</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[context-api]]></category>
            <dc:creator><![CDATA[Hossein Ahmadi]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 03:31:15 GMT</pubDate>
            <atom:updated>2020-06-24T06:21:01.236Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[React Hooks: How to use useEffect()]]></title>
            <link>https://javascript.plainenglish.io/react-hooks-how-to-use-useeffect-ecea3e90d84f?source=rss-ee208eb13e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecea3e90d84f</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hossein Ahmadi]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 22:37:17 GMT</pubDate>
            <atom:updated>2019-08-26T22:37:17.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzlu13kKwDzlkV1031c7fg.jpeg" /></figure><h4>Review</h4><p>In the last article I’ve introduced React Hook and basic principals of useState() and finally we made our first custom hook. As I mentioned in <a href="https://medium.com/@hossein98.ahmadi/react-hooks-for-beginners-sweet-and-a-little-complex-31a1225bd2f7">React Hooks for beginners, Sweet and a little complex</a> after understanding core concepts of useState() we’re going to inquire more in hooks and the next subject is useEffect(). One of the most important and useful parts of hooks that every developer needs to work with it if chooses hooks. It’s a little challenging and a little bit hard to understand BUT if you think in hooks way, I assure you enjoy writing your codes using it.</p><p>Stay with me and I hope you understand useEffect() method and its usage at the end of this article.</p><h4>About useEffect()</h4><p>If you refer to ReactJS official documents and search for useEffect in the hook section first tip you’ll see is this:</p><blockquote>If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.</blockquote><p>Lifecycle methods in class-based components are very important. Sometimes you want to fetch some data from an API when rendering a component, sometimes you want to do specific action when your component updates. Most important methods are <strong>componentDidMount</strong> and <strong>componentDidUpdate</strong>.</p><p>Do you remember a very important thing that was mentioned in last article?</p><blockquote>Hooks are something that let you write Functional Components and still hook into class-based features and use them.</blockquote><p>UseState let us to bring states to functional components. States and lifecycle methods are 2 big parts of class-based component’s features. UseEffect allow us to handle our logic in lifecycle methods. From the name of it you understand that useEffect will be called every time something affects your component.</p><p>Awesome! So obvious that it’s definition of componentDidMount and componentDidUpdate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sht4ASpcZlfNf3Ch" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Different uses of useEffect()</h4><p>Okay! Let’s write some code to go deeply through useEffect(). In this part I would like to use ReactJS docs example with some important changes to practice and see usage of useState() and useEffect() clearly. Assume we want to declare a property in state what is an object. And has 2 properties: name and familyName. Initial state would be “name” and “family” and after rendering the component it should be changed to something else.</p><blockquote>NOTE: You can trace your states by React dev tools extension in Firefox or Chrome.</blockquote><p><strong>First step: Define states</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c097aed15a939dfde83a918d6cc57dd3/href">https://medium.com/media/c097aed15a939dfde83a918d6cc57dd3/href</a></iframe><p><strong>Second Step: Define useEffect()</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1970d5b1984ba73573772285d46d3aa0/href">https://medium.com/media/1970d5b1984ba73573772285d46d3aa0/href</a></iframe><p>As you see in the code the argument of useEffect() is a function that handles your actions when something affects your component. Let’s check the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uk7jZQIN2DA0kQ3AH8bIhw.png" /></figure><p>Great! Like me you should see the name and familyName you choose in state.</p><p>But let’s check something else. I want to log a special sentence in useEffect to see how many times it will be called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/832eabeed4daf46757efaf966ebaa3ff/href">https://medium.com/media/832eabeed4daf46757efaf966ebaa3ff/href</a></iframe><p>And the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*GvALLBONI3vsNVR9ytutPQ.jpeg" /></figure><p>Oops! Same as me you understand that useEffect has been called every time that component changed. This isn’t what we’re looking for. Our useEffect method is acting like componentDidUpdate now. If you’re familiar with componentDidUpdate we can control when it should act by conditions. Here in useEffect you can pass an array as the second argument. This array clearly tells react that just call useEffect when fields in me has been changed. So if you put ”name” in the array and pass it as second argument of useEffect(); your method will be called just when “name” changes.</p><p>Still this isn’t our answer. We want componentDidMount! To tell useEffect to act like componentDidMount just pass an empty array and everything will be perfect. Let’s check it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40f8f9ba214b992bbc919acc53be1179/href">https://medium.com/media/40f8f9ba214b992bbc919acc53be1179/href</a></iframe><p>And our logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*uLDds2pHLGLQdXPJ0d_IHg.jpeg" /></figure><p>Great! Now we have used different types of useEffect() and I hope you’ve realized the core concepts of useEffect().</p><h4>Fetch data with useEffect</h4><p>We want to go further and use our knowledge about React Hooks. We want to do an actual and useful task that all of us will be faced in real projects: Fetching Data from an API. Before we move forward you should know some tips:</p><blockquote>1. We use axios to fetch our API. It’s too cleaner and easy to use. You can read about it here: <a href="https://github.com/axios/axios">Axios GitHub</a></blockquote><blockquote>2. We use rest countries global API. URL is: ‘https://restcountries.eu/rest/v2/all’</blockquote><p>Okay! All setups are nice and enough. Our task here is to get list of countries from our API and show them in a bullet list.</p><p>We need to provide 3 variables in our state:</p><ol><li><strong>Countries:</strong> list of our country to show them</li><li><strong>Load:</strong> to show a loading text until our fetch process completes. (to avoid async/await TypeErrors)</li><li><strong>Error:</strong> to show error returns from our fetch method instead of the country list</li></ol><p>Alright! Declare our state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4780afbe019a113d0c1bd016898cd59/href">https://medium.com/media/a4780afbe019a113d0c1bd016898cd59/href</a></iframe><p>Good! Now we fetch our API using axios in useEffect(). Don’t forget to pass an empty array as second argument because we want our useEffect act like componentDidMount.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0005509318be23b68df1d9d5ce07bdd4/href">https://medium.com/media/0005509318be23b68df1d9d5ce07bdd4/href</a></iframe><p>Our load initial state is a Boolean type <strong><em>false</em></strong> and our error is undefined. When our component mounted, we fetch our API. If API returns status code 200 or OK, we set our countries array by returned data. But if our fetch process fails, we set an error equal to retuned error. In both cases we set our load “<strong><em>true</em></strong>” to show visitors the final result. And finally, our last step:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2398aab30aa0298d0b1fbf049558cd3/href">https://medium.com/media/c2398aab30aa0298d0b1fbf049558cd3/href</a></iframe><p>Great! We’re Done! We successfully fetched API in a functional component thanks to useEffect and handled loading and error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKgtj7ME8L0wJYFsieiMig.png" /></figure><h4>Make our code cleaner</h4><p>We can make our code cleaner. Let’s move our fetch method to another file and implement a get method for our entire project. Before we go further it’s important to know we’re going to use promises because fetching API takes time and we want to avoid TypeErrors. You can read about promises in <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261">Master the JavaScript Interview: What is a Promise?</a> By Eric Elliott.</p><p>As mentioned by Eric Elliott:</p><blockquote>A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.</blockquote><p>So, we create a promise an tell him to do our action. Promise resolve us some answer or data if the action completes successfully or reject us with some reason if action fails. Now let’s create our getItems method in another file, for example generalMethods.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/723927a61828e244adfe4de96a747518/href">https://medium.com/media/723927a61828e244adfe4de96a747518/href</a></iframe><p>Now we can import and use it every time we want to fetch a get API. We just need to pass our URL. Be aware that now we can remove our load state and ignore it but don’t do it. Maybe our fetch process takes some time because of user’s internet speed or our server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba643926d068e230509b17a3cee2af20/href">https://medium.com/media/ba643926d068e230509b17a3cee2af20/href</a></iframe><p>Nice and Clear!</p><h4>Final talk</h4><p>In my 2 articles about hook I tried to show you power and benefits of functional components and hooks. I understand if you are a little confused and have fear about using hooks. It’s normal. Class-based components are ruling in react for about 5 years and breaking the habits is too hard and frightening. But you should hit the target. Move slowly. Challenge yourself. Implement your classes by hooks in another project. Try to beat your habits and test hooks. I assure you’ll enjoy it. In next articles I’ll explain useReducer for developers who are using redux. And we will create a real web application using only functional components and hooks. You’ll see the modularity and beauty of hooks in next articles clearly.</p><p>If you liked this article and it was useful for you don’t forget to clap and feel free to contact me by email: <a href="/service/mailto:hossein.ahmadi98@youtlook.com">hossein.ahmadi98@outlook.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecea3e90d84f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-hooks-how-to-use-useeffect-ecea3e90d84f">React Hooks: How to use useEffect()</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks for beginners, Sweet and a little complex]]></title>
            <link>https://medium.com/weekly-webtips/react-hooks-for-beginners-sweet-and-a-little-complex-31a1225bd2f7?source=rss-ee208eb13e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/31a1225bd2f7</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs-development]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <dc:creator><![CDATA[Hossein Ahmadi]]></dc:creator>
            <pubDate>Sun, 07 Jul 2019 08:01:32 GMT</pubDate>
            <atom:updated>2020-06-10T10:49:47.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*HrbQKxxuR_jWmSOkz7-lAA.jpeg" /></figure><h4><strong>What are Hooks?</strong></h4><p>React has been introduced around 5 years ago and nowadays is one of the most popular JS front end libraries. React with all of its great and amazing features walked through developer’s life and right now that I’m writing for you earned +132k stars in GitHub.</p><p>Main concept of react is based on Components. Something that let you to write reusable codes and make your project clean. As you know there are 2 types of components in react: Class-Based Components and Functional Components. Class-Based components are a little older than functional components and as we except they have some excluded features that functional components can’t use them.</p><p>But functional components are cleaner and faster and sweeter than classes. So, React has introduced Hooks. Hooks are something that let you write Functional Components and still hook into class-based features and use them. Great! Now with React Hooks we can write cleaner and simpler components by using functions and still use wonderful features of Class-based components, Specifically States and Stateful Logic!</p><h4><strong>Why should we use hooks and functional-components?</strong></h4><p>If you walk through react official documents and read about Hooks and Functional-Components you can see some enough reasons to use them. But let me show you some real examples that help you understand reasons deeply.</p><p><strong>First. Less and Cleaner Code: </strong>We want to build a component that renders a title and a subtitle. First, we write it by class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea2fbd7117005b31cb7c632011f1a284/href">https://medium.com/media/ea2fbd7117005b31cb7c632011f1a284/href</a></iframe><p>Now our functional Component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ecebe661a2e7c541371963891813cf8/href">https://medium.com/media/4ecebe661a2e7c541371963891813cf8/href</a></iframe><p>Alright! I don’t explain more. It’s clear which one is cleaner!</p><p><strong>Second. Hierarchy and stateful logics: </strong>As mentioned in react docs:</p><blockquote>React doesn’t offer a way to “attach” reusable behavior to a component</blockquote><p>What does it mean? Think about 3 components that everyone contains a form and every form contains a name filed. You store the value of your input in state of your components. So, you have 3 class-based components with state (includes name) and handleNameChange handler. Instead of writing this same code over and over every time you want to use the name field in your project just use hooks! Write one hook and import it in any functional component and you can use the name and its handler behavior!</p><p><strong>Third. Class-Based Components are complex!: </strong>Yes! Classes are complex. When you want to write a class-based component you need to understand core concepts of word “this”, lifecycles like componentDidMount or componentDidUpdate, binding methods and so on. But in functional components you just work with functions! Specially arrow functions. There is no “this” and There is no binding. But there is no state and lifecycle neither! What if we want to fetch an API after mounting our component? What if we want to have forms and do validation and something with their value in state? Don’t worry. Just use hooks useState instead of states and setState and use Effect instead of lifecycle methods.</p><p><strong>Fourth. Sweet experience for developers that move up to down: </strong>For someone like me that move in the project tree and develops step by step from UP to DOWN, using react hooks can be a great experience. Let me explain more. Up to down means I write my bigger components first. So, I use a pattern in all of my projects that tells me: Complete base of your navigation and routing first, do your job in bigger components and then hit other small components.</p><p>So, when I start my project I’ll go to my router. But for testing and verifying my router I need some components! Then I have to create my base components first. As we see above, functional components are cleaner and faster therefore I use them to speed up my development. After completing router, I head back to my base and important components and Ooops!!! I need form in this one and I have to convert it to class! I need stateful logic in this one and I have to convert it to class! But now with hook, developing react apps can be more enjoyable for me and people like me!</p><blockquote><strong>Note 1:</strong> You don’t have to use hooks! There isn’t any pressure by react team on you to migrate and convert your codes to use hooks. Even they encourage you to read and search about hooks and walk slowly through new world of react. You can write and use hooks beside your class-based components (NOT IN THEM) to see how it works and which you prefer.</blockquote><blockquote><strong>Note 2:</strong> There’s discuss about the performance of functional and class-based components. You can read this great article by Philippe Lehoux: <a href="https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f">45% Faster React Functional Components, Now</a></blockquote><blockquote><strong>Note 3:</strong> Don’t forget to read some important rules of using hooks in this article in official documents: <a href="https://reactjs.org/docs/hooks-rules.html">Rules of Hooks</a></blockquote><h4><strong>Definition of useState</strong></h4><p>And now let’s see some simple practical codes using useState in react. See this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01658627e882c2aaf7fe7ac2d8ccbea3/href">https://medium.com/media/01658627e882c2aaf7fe7ac2d8ccbea3/href</a></iframe><p>This is react docs example for useState and counts from zero by clicking on the button. Class type of code is here too:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23305fa14adccefeb07483dd8b6fa0ab/href">https://medium.com/media/23305fa14adccefeb07483dd8b6fa0ab/href</a></iframe><p>You see useState(), count, setCount and some brackets.</p><p><strong>UseState():</strong> this is a function that is provided by react team in react library and you have to import it first. Returns an array and its argument is the initial value of state.</p><p><strong>Count:</strong> the name of our variable in state</p><p><strong>SetCount: </strong>a function that implements our stateful logic. The input of setCount is our state’s new value.</p><p><strong>Brackets:</strong> brackets are some simple array destructuring! You can read about this in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring assignment in JavaScript</a>. As I mentioned above every useState() returns an array! So, by using this bracket we are using first value of array ([0]) as value of our state and second ([1]) is the method we define to change our state.</p><p>Therefore, in this example we’re telling that our component has state that includes count and we want to handle changes of it by setCount method.</p><h4><strong>Some examples of useState and our own hooks</strong></h4><p>Now let me show you some useful implementation of useState. In this example we create our hooks by using useState, so you can see the reusability and flexibility of hooks too.</p><p>Consider we want to have a counter that receives start, finish and step and count by clicking a button. This is our main component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc4713c4d89aa47a62d366f07c955494/href">https://medium.com/media/dc4713c4d89aa47a62d366f07c955494/href</a></iframe><p>Please note that useCounter is our custom hook that receives 3 arguments: start, finish and step.</p><p>Our array destruction means that our hook returns an array that first item is value of count and second one is the method of changing state (Our State Logic).So we use this method- with our arbitrary name of handleCount- as the onClick event handler. Therefore, it’s time to see our custom hook implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29fb350758c6854ba3d46c71f3e31af0/href">https://medium.com/media/29fb350758c6854ba3d46c71f3e31af0/href</a></iframe><p>We see 3 parts in this code:</p><ol><li>Definition of our state: from what you have read in this article this line means: we have a count variable in our state that its initial value is value of “start” and we want to change our state by setCount method.</li><li>Implementation of our handleCount method. We use a condition to check if we reached our finish amount or not. Then we use setCount to change the value of count according to if condition result.</li><li>Return our custom hook array: as you see first is the value of count and second is our handleCount method.</li></ol><p>This is what we see when we run our app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*o0nI5wY4-iV0snacZitLkw.gif" /><figcaption>Result of our codes</figcaption></figure><h4><strong>Wrap Up</strong></h4><p>Awesome! Everything in this article is the base and core concept of react hooks for beginners and developers who are afraid of changes. You can read more about this subjects or other subjects about hooks in React Documentation and other sources. I’ll try to describe useEffect in the future because it’s not possible to cover it in this article. Just walk through Hooks and start to rewrite some of your codes with react new feature to see its power and sweetness.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31a1225bd2f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/react-hooks-for-beginners-sweet-and-a-little-complex-31a1225bd2f7">React Hooks for beginners, Sweet and a little complex</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>