<?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 Bartosz Szczeciński on Medium]]></title>
        <description><![CDATA[Stories by Bartosz Szczeciński on Medium]]></description>
        <link>https://medium.com/@baphemot?source=rss-a5f578f5b81a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4LUSy4jH_AaeVgBsXKEorA.png</url>
            <title>Stories by Bartosz Szczeciński on Medium</title>
            <link>https://medium.com/@baphemot?source=rss-a5f578f5b81a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 17:42:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baphemot/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[A React job interview — recruiter perspective.]]></title>
            <link>https://medium.com/@baphemot/a-react-job-interview-recruiter-perspective-f1096f54dd16?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1096f54dd16</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[job-interview]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Wed, 10 Oct 2018 05:57:26 GMT</pubDate>
            <atom:updated>2018-11-21T05:35:09.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>A React job interview — recruiter perspective.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQNFrJwbmP7AmaSU-rxuBg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rawpixel">rawpixel</a> via unsplash</figcaption></figure><blockquote><strong>Important</strong><br>This article is not a list of questions to expect on an interview and complete answers to them. The point of this post is to show what questions I ask, what I’m looking for in an answer and why there are no bad answers.<br>If you want a list of “best react interview questions 2018” check out <a href="https://github.com/sudheerj/reactjs-interview-questions">https://github.com/sudheerj/reactjs-interview-questions</a></blockquote><p>Part of my job is performing the so called “technical interviews” during which I evaluate potential candidates that are applying for a “Frontend Developer with React” position.</p><p>If you’ve ever Googled “react interview questions” (or any other “[tech] interview questions”) you’ve probably seen countless results of “top 10 react interview questions” which are either outdated or rehash the same “what’s the difference between state and props” or “what’s virtual dom” questions.</p><p>Knowing answers to those questions <em>should not</em> be the basis on which the interviewer decides to hire or not. That’s something a candidate <strong>needs to know,</strong> understand and implement in his daily work. If you’re a candidate being asked those questions either the person interviewing you has no tech background (a HR person or “linkedin headhunter”) or they see this as a formality.</p><p>The interview should not be a waste of time. It should give you an idea about the candidate past experience, past knowledge and development opportunities. The candidate should learn about your organisation and project (if possible) and get feedback on his performance vs. your expectations. There should be no bad answers in a job interview (unless the questions is strictly technical) — an answer should give you an insight into the person thought process.</p><p><strong>The article is written from the perspective of the person conducting the interview!</strong></p><h3>Let’s get to know each other</h3><p>In many cases the interview will be conducted via Skype or other voice (or voice+video) communication platform. Getting to know the potential hire is a good way to get them to open up.</p><h4>Can you tell me a bit about your previous job, how did you fit in the team? What were your responsibilities?</h4><p>Knowing what the person did at his previous work place (if he’s allowed to share) is a good way to start. This gives you some basic idea about the previous work experience: soft skills (“I was a sole developer on …”, “I, and my colleagues…”, “I managed a team of 6 developers …”) and hard skills (“… we created an application used by 1 mil people”, “… I helped optimize rendering time of the application”, “… created dozens automated tests”).</p><h4>What’s the main selling point of React <em>to you. </em>Why did <em>you</em> chose to go with React?</h4><p>I don’t expect you to mention JSX, VDOM etc. — we already get that from reading the “features” blurb on the homepage. Why did *you* start using React?</p><p>Was it because of the “easy to learn, hard to master” API (which <em>is</em> quite small when you compare it to other solutions)? Good — say that, it means you’re willing to learn new things, and learn them as you go.</p><p>Was it because of the “job opportunities”? Good — you’re a person that can adapt to the market and will have no issues moving on in 5 years when The Next Big Framework comes. We have enough of jQuery developers already.</p><p>Think of this a bit like an “elevator pitch” scenario (you are in an elevator with your boss and need to convince him to use new technology before they get out on his 20th floor). I wan’t to know you know what React has to offer that can benefit the client and you, the developer.</p><h3>Let’s start to get a bit more technical</h3><p>As I mentioned in one of the opening paragraphs — I’m not going to ask you what VDOM is. We know it, I will however ask you …</p><h4>What is JSX and how come we can write it in our JavaScript code — how do the browser recognize it?</h4><p>You know this — JSX is just a notation, that Facebook popularized, which — thanks to tools like Babel / TSC — allows us to write React.createElement calls in a form that’s a bit more pleasant to the eye.</p><p>Why do I ask this question? I want to know if you understand the technical side of JSX and all the limitations that come from it: why do we need to import React from &#39;react&#39; on the top of the file even if we don’t use React in our code; why can’t the component directly return multiple elements.</p><p><strong>Bonus question: why do the Component names in JSX start with capital letter?<br></strong>Answering that this is how React knows to render a Component, and not a HTML Element should be good enough.</p><p>Bonus points: there are exceptions to that rule. E.g. assigning a component to this.component and then doing &lt;this.component /&gt; will work.</p><h4>What are the main 2 types of components you can declare in React, and when would you use one over another.</h4><p>Some people will think this is about presentation and container components, but this is more about React.Component and function components.</p><p>A proper answer should mention life cycle methods and component state.</p><h4>Since we mentioned life cycle — can you walk me through the cycle of mounting a stateful component? What functions are called in what order? Where would you place a request for data from the API? Why?</h4><p>Ok, that’s a long one. Feel free to break it into two smaller ones. You’re now thinking “but you said you don’t ask about life cycle!”. I don’t, I don’t care about the life cycle. I care about the changes that happened in the life cycle in the very recent months.</p><p>If the answer contains componentWillMount you can assume that the person has been either working with an older version of React exclusively, or has done some outdated tutorials. Both cases should rise some concerns. getDerivedStateFromProps is what you’re looking for.</p><p>Bonus points: differences in the way the process goes on server-side is mentioned.</p><p>Same goes for the question about data fetching — componentDidMount is the one you want to say/hear.</p><p><strong>Bonus question: why </strong><strong>componentDidMount and not </strong><strong>constructor?<br></strong>Two reasons you want to hear are: “the data will not be there before render happens” — although not the main reason, it shows you that the person understands the way components are handled; “with the new asynchronous rendering in React Fiber …” — someone has been doing his homework.</p><h4>We mentioned fetching data from an API — how would you go about making sure the data is not re-fetched when the component is re-mounted?</h4><p>We assume “cache invalidation” is not a thing. This one is not strictly React related, but if the answer is limited to React it’s also good — maybe they’ve worked with GraphQL which does the heavy lifting for you?</p><p>I ask this to see if the candidate understands the idea of not-coupling the UI and other layers in an application. An API that’s external to the React structure can be mentioned.</p><h4>Can you explain the idea of “lifting the state up”?</h4><p>Ok, I do ask some typical React questions. This one is crucial though, it will allow you to give the candidate some breathing room.</p><p>Answers ranging from “it allows to pass data between siblings” to “it allows you to have more pure-presentational components, which make re-usability easier” are preferred. Redux might get mentioned here, though that could as well be a bad thing, because it signifies that the candidate just goes with whatever the community recommends without understanding why they needs it.</p><p><strong>Bonus question: how would you go about passing data across multiple levels of depth, without passing it from component to component?</strong><br>Context has become mainstream ever since React 16.3 — it was there before, but the documentation was lacking (on purpose). Being able to explain how context works (and at the same time showing knowledge of the function-as-child pattern) is a plus.</p><p>If Redux / MobX gets a mention here, it’s also good.</p><h3>React ecosystem</h3><p>Developing React apps is part of the process — there’s a lot more to it: debugging, testing, documenting.</p><h4>How would you go about debugging an issue in React code; what tools have you used? How would you go about investigating why a component does not re-render?</h4><p>Everyone should be familiar with the basic tools like a linter (eslint, jslint) and debuggers (React Developer Tools).</p><p>Using RDT to debug the issue by checking if the component state/props are properly set is a good answer, mentioning using the Developer Tools to setup breakpoints is also a good one.</p><h4>What testing tools have you used to write unit / E2E tests? What’s snapshot testing and what are the benefits of it?</h4><p>In most cases tests are a “necessary evil” but those are things we need. There are many good answers here: karma, mocha, jasmin, jest, cypres, selenium, enzyme, react-test-library etc. The worst thing is the candidate answers “we didn’t do unit tests at my previous company, only manual tests”.</p><p>The snapshot testing part also depends on what you use in your project; if you don’t find it beneficial, don’t ask about it. But if you do, fast and easy regression tests for the UI layer (generated HTML + CSS).</p><h3>Small code challenges</h3><p>When possible, I also do small code challenges which should take no more than a minute or two to fix/explain, e.g.:</p><pre>/** * What is wrong with this example, and how would you go  <br>* about fixing or improving the component? <br>*/ </pre><pre>class App extends React.Component {  <br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      name: this.props.name || &#39;Anonymous&#39;<br>    }<br>  }    </pre><pre>  render() {<br>    return (<br>      &lt;p&gt;Hello {this.state.name}&lt;/p&gt;<br>    );  <br>  }<br>}</pre><p>There are multiple ways to solve it: remove the state and use props, implement getDerivedStateFromProps or (preferably) change to a function components.</p><pre>/**<br> * Can you explain the differences between all those ways<br> * of passing function to a component?<br> *<br> * What happens when you click each of the buttons?<br> */</pre><pre>class App extends React.Component {<br>  <br>  constructor() {<br>    super(); <br>    this.name = &#39;MyComponent&#39;;<br>    <br>    this.handleClick2 = this.handleClick1.bind(this);<br>  }<br>  <br>  handleClick1() {<br>    alert(this.name);<br>  }<br>  <br>  handleClick3 = () =&gt; alert(this.name);</pre><pre>render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;button onClick={this.handleClick1()}&gt;click 1&lt;/button&gt;<br>        &lt;button onClick={this.handleClick1}&gt;click 2&lt;/button&gt;<br>        &lt;button onClick={this.handleClick2}&gt;click 3&lt;/button&gt;<br>        &lt;button onClick={this.handleClick3}&gt;click 4&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>This one takes a bit more, because there’s just more code. If the candidate answers correctly follow up with “why?”. Why will click 2 work the way it works?</p><p>Not a React question, if someone starts with “because in React …” it means that they don’t really understand the JS event loop.</p><pre>/**<br> * What&#39;s the issue with this component. Why?<br> * How would you go about fixing it?<br> */</pre><pre>class App extends React.Component {</pre><pre>state = { search: &#39;&#39; }</pre><pre>handleChange = event =&gt; {</pre><pre>/**<br>     * This is a simple implementation of a &quot;debounce&quot; function,<br>     * which will queue an expression to be called in 250ms and<br>     * cancel any pending queued expressions. This way we can <br>     * delay the call 250ms after the user has stoped typing.<br>     */<br>    clearTimeout(this.timeout);<br>    this.timeout = setTimeout(() =&gt; {<br>      this.setState({<br>        search: event.target.value<br>      })<br>    }, 250);<br>  }</pre><pre>render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;input type=&quot;text&quot; onChange={this.handleChange} /&gt;<br>        {this.state.search ? &lt;p&gt;Search for: {this.state.search}&lt;/p&gt; : null}<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><p>OK, this one will need some explaining. There’s no error in the debounce function. The way the application is expected to work, is it will update the state 250 ms after the user has stooped typing, and then render the string “Search for: …”.</p><p>The issue here is that the event is a SyntheticEvent in React, and if the interaction with it is delayed (e.g. via setTimeout) it will be cleared and the .target.value reference will no longer be valid.</p><p><strong>Bonus points: the candidate is able to explain why that is.</strong></p><h3>We’re done with the tech questions.</h3><p>This should be enough to give you some idea about the technical skills of the candidate. You should still have some time left for more open-ended questions.</p><h4>What was the biggest problem you’ve faced on your past projects; what was your biggest achievement?</h4><p>This goes back to the very first question — the answer can vary from developer to developer and position to position. A junior developer will say his biggest problem was getting thrown in a complex process, but they were able to conquer it. Someone looking for a more senior position will explain how they optimized the app performance, and someone that can lead teams explain how they’ve improved velocity by doing pair programming.</p><h4>If you had unlimited time budget and could fix / improve / change one thing in your last project, what would it be and why?</h4><p>And another open ended question, answer to which depends on what you’re looking for in the candidate. Will they try to replace Redux with MobX? Improve the testing setup? Write better documentation?</p><h3>Reversing the tables and feedback</h3><p>Now’s the time to change the roles. You probably have a solid idea about the candidate skills and potential to grow. Let him ask the questions — not only will it allow him to get to know the company and product more, the questions theyask might give you some indication about the direction they want’s to grow in.</p><p><a href="https://medium.com/u/ec0b3a253e09">Carl Vitullo</a> wrote some good articles on the topic of what questions to ask your potential employer, I’ll refer you to those — be ready to answer them, or say that you can’t on given step due to NDA requirements etc.:</p><ul><li><a href="https://medium.com/@vcarl/questions-to-ask-your-interviewer-82a26e67ce6c">onboarding and the workplace</a></li><li><a href="https://medium.com/@vcarl/questions-to-ask-your-interviewer-development-and-emergencies-f7fbc4519e5b">development and emergencies</a></li><li><a href="https://medium.com/@vcarl/questions-to-ask-your-interviewer-growth-c88eed119ce2">growth</a></li></ul><h4>Give feedback</h4><p>If the candidate under-performed on some questions or got them wrong (or different than you would expect) — you might want to clarify those at this point. Don’t make it sound like you’re patronizing the person, just explain the problems you’ve noticed — offer solution and some resources they can use to improve.</p><p>If the rest of the recruitment process is up to you, tell them you will get back o them in X days, if not, tell them that someone from your company will do that. If you know the process will take longer than 2–3 days, tell them that. IT is a big market at this point, and the candidate might have done multiple interviews — they might not wait for you to get back before accepting another offer.</p><p><strong>Do not ignore the candidate — that’s literally the main complaint people share on social media.</strong></p><blockquote>The opinions expressed in this blog post are those of my own and do not reflect the opinions of any of my past or current employer, client or collaborator.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1096f54dd16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding frontend — security]]></title>
            <link>https://medium.com/@baphemot/understanding-react-frontend-security-4963d35feea7?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4963d35feea7</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Sun, 23 Sep 2018 13:08:53 GMT</pubDate>
            <atom:updated>2018-09-23T13:59:44.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*aVMCrBpJ2IOJMmebH3FAAQ.jpeg" /><figcaption>Source: <a href="http://www.itv.com/news/meridian/2016-04-25/simons-blog-funny-signs/">http://www.itv.com/news/meridian/2016-04-25/simons-blog-funny-signs/</a></figcaption></figure><p>The topic of security on the frontend part can be separated into two purposes:</p><ul><li>keeping your client and their data secure</li><li>keeping your clients away from things they should not have access to</li></ul><p>The first part is a very vast topic that covers things like cross-site-scripting (XSS), cross-site-request-forgery (CSRF), CORS and other topics related to how browser keep your data from leaking out to attacker or preventing attacker from performing actions in your name.</p><p>The second part is more concerned with “how do I limit my users from accessing certain parts of my site” — things like members only section, admin panel etc.</p><h3>Are variables in browser secure?</h3><p>Your first idea might be “I’m going to create an isAdmin variable, set it to true whenever an admin authenticates and then check it in my application.</p><p>But once you implemented that solution — a question hits you — “What if the user just opens developer tools and changes it to true on his end? How can I prevent that? Should I use localStorage, sessionStorage or is there something more secure?”</p><p>We need to make one thing clear — everything you put in the client browser can be easily changed by the client. The browser — by default — gives an attacker all the tools he needs. He can open the devtools and change all the in-memory variables. He can manipulate localStorage, sessionStorage, cookies and with the correct extensions even React components state. He can also substitute the response of the auth endopint and just make it response with {isAdmin: true} every time.</p><p>You might think that you could use some form of encoding — either roll out your own, or use JWT which you can then verify in the browser for any modifications. This approach is also flawed, because you would need to make the browser aware of the mechanism (keys) used to generate the signature — else the attacker would just need to make up his own keys, change the isAdmin field in the JWT and sign it with his key — the signature is valid, the browser accepts the JWT as legit and trusts that the user is an admin.</p><h3>How do I prevent the user from accessing non-public parts of my site?</h3><p>You do it exactly as you though to do it — you create a variable, set it to true for admins only and once the check passes, show the admin only content.</p><p>“Ok, that’s not secure at all — everyone can then go to the admin page and delete everything!” you scream.</p><p>Fair — but only if you implement your application in a bad way. The frontend part should not be concerned with the validity or not of credentials provided. It should always accept the data as “true” and just render all the data it is passed.</p><p>It it’s the backend job to perform this validation!</p><p>Your UI can have a “Delete database” button. You might even try to hide it with some logic, but an attacker can download the JavaScript code and look for all endpoints — he will find <a href="http://example/">http://example</a>.com/api/database/delete URL (this is only for the sake of the example, you should always use CRUD notation anyway :)) and call it manually. If this operation ends up in deleting your database — you seriously need to add more security to your application.</p><p>In similar vein, your application can render members only content under /members/blogpost/read-up-on-all-the-new-things — the attacker can always navigate to it directly. If he were to see the content, that means your API (or other forms of content delivery) is not designed correctly — the attacker should be then redirected to /sign-up right away, or in the worst case he should see an blog post template without any content loaded.</p><h3>Backend is the deciding factor</h3><p>In both cases above, the attacker is able to get into gated-off content, but he is unable to perform the operation associated with the action. All of them should communicate with the backend and contain some form of authentication (am I who I say I am) and authorization (can I perform this action) mechanisms.</p><p>If the action is permitted, perform it and reply with a proper HTTP code (e.g. 200), if it’s not permitted, reply with an HTTP error code — e.g. 401 (not authenticated) or 403 (not authorized). Your frontend should respond to this and either let the user know he’s doing something he has no authorization to (show an error message, redirect to a login screen) or just fail gracefully (render an template with no content or *gasp!* — Published at: &lt;date&gt;undefined&lt;/date&gt;).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4963d35feea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s Server Side Rendering and do I need it?]]></title>
            <link>https://medium.com/@baphemot/whats-server-side-rendering-and-do-i-need-it-cb42dc059b38?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb42dc059b38</guid>
            <category><![CDATA[universal-app]]></category>
            <category><![CDATA[isomorphic-applications]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Sat, 01 Sep 2018 15:46:29 GMT</pubDate>
            <atom:updated>2018-09-01T17:16:57.847Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction of modern JavaScript frameworks / libraries that focus on creating interactive websites or Single Page Applications the way that pages are displayed to a visitor has changed a lot.</p><p>Before the advent of applications fully generated by JS, in the browser, HTML was returned in response to the HTTP call — be it by returning a static HTML content file, or by processing the response via server side languages (such as PHP, Python or Java) and responding in a more dynamic way.</p><p>A solution like this allows us to deliver responsive sites that work a lot faster than standard request-response model by removing the “request travel time”.</p><p>A typical response sent by the server when requesting a React site will look something like this:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;link rel=&quot;shortcut icon&quot; href=&quot;/favicon.ico&quot;&gt;<br>    &lt;title&gt;React App&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;/app.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>After fetching this response our browser will also fetch the app.js “bundle” which contains our application and after a second or two render the complete page.</p><p>At this moment we can use our browser HTML Inspector to view the complete rendered HTML, but when we view the actual source we will see nothing more than the above HTML code.</p><h3>Why is this an issue?</h3><p>While this behavior will not be a problem for most our users or when developing the application it will become an issue if:</p><ul><li>the end user is using a <strong>slow internet connection</strong>, especially mobile connection,</li><li>the end user is running an <strong>underpowered device</strong>, for example an older generation mobile device,</li></ul><p>If your target demographic falls into one of those groups they will have a bad experience using the site — for example will have to wait a lot longer, staring at the “Loading …” (or even worse — a blank screen) message.</p><p>“OK, but my target demographic is not in any of those groups, should I still care?”</p><p>There’s one more important thing you should consider when going with a client-side rendered app: <strong>search engines</strong> and <strong>social networks presence</strong>.</p><p>Currently, of all the search engines only Google has limited capabilities to render and JS site before indexing it. In addition, while Google will be able to render the index page of your website it is known to have issues navigating around sites with a router implementation.</p><p>This means that <strong>your site will have very hard time trying to get top position in the search results</strong> in anything but Google.</p><p>The same issue is visible in social platforms such as <strong>Facebook </strong>— when sharing a link to your site neither the title nor the thumbnail will render properly.</p><h3>How to solve the issue</h3><p>There are a few ways we can solve the issue.</p><h4>A — Consider having your key pages as static</h4><p>When you’re creating an platform that requires the users to login, and not providing the content to not-signed in users you might decide to<strong> create your public facing sites (like the index, “about us”, “contact us” etc.) pages as static HTML</strong>, and not have them rendered by JS.</p><p>Since your content is gated by login requirements it will not be indexed by search engines or shared in social media.</p><h4>B — Generate parts of your application as HTML pages when running the build process</h4><p>Libraries like <a href="https://github.com/geelen/react-snapshot">react-snapshot</a> can be added to your project, used to generate HTML copies of your application pages and save them to a specified folder. You can then deploy this folder alongside your JS bundle. This way, the HTML will be served along with the response allowing your site to be accessible by users with JavaScript disabled, search engines etc.</p><p>In most cases, configuration of react-snapshot is as simple as adding the library to your project, and altering the build script by calling it at the end:</p><pre>&quot;build&quot;: &quot;webpack &amp;&amp; react-snapshot --build-dir static&quot;</pre><p>The downside of this solution is that all the content we want to generate must be available at build time — we can’t query any APIs to get it, we can’t pre-generate content that depends on user provided data (e.g. as URL).</p><h4>C — Create a server-side rendered application in JS</h4><p>One of the big selling point of the current generation of JS applications is the fact, that they can be ran on both the client (browser) and on server — this allows us to generate HTML for pages that are more dynamic — which content is not known at build time. This is often referred to as “isomorphic” or “universal” application.</p><p>Two of the most popular solutions that provide SSR for React are:</p><ul><li>next.js — <a href="https://github.com/zeit/next.js/">https://github.com/zeit/next.js/</a></li><li>Gatsby — <a href="https://github.com/gatsbyjs/gatsby">https://github.com/gatsbyjs/gatsby</a></li></ul><h3>Create your own custom SSR implementation</h3><p>Important: If you’re willing to try to and create your own SSR implementation for your React applications, you’re going to need to be able to run a node backend for your server. You will not be able to deploy this solution to static host like github pages.</p><p>First step we’re going to take is to create an application just like you would with any other React application.</p><p>Let’s create our entry point:</p><pre>// index.js<br>import React from &#39;react&#39;;<br>import { render } from &#39;react-dom&#39;;<br>import App from &#39;./App.js&#39;;</pre><pre>render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));</pre><p>And the App component:</p><pre>// App.js<br>import React from &#39;react&#39;;</pre><pre>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      Welcome to SSR powered React application!<br>    &lt;/div&gt;<br>  );<br>}</pre><p>And our “shell” to load our application:</p><pre>// index.html<br>&lt;!doctype html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;/bundle.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>As you see our application is quite simple. We’re not going to go through all the steps needed to generate the proper webpack+babel setup in this article.</p><p>If you run the application in its current state, you will notice the welcome message on screen, and viewing the source you will see the content of index.html file, without the actual welcome message. To solve this issue let’s add server side rendering. First, we will need to add 3packages:</p><pre>yarn add express pug babel-node --save-dev</pre><p>Express is a powerful webserver for node, pug is a templating engine we can use with express, and babel-node is a wrapper for node, which allows it to perform code transpilation on the fly.</p><p>First, we will make a copy of our index.html file, and save it as index.pug:</p><pre>// index.pug<br>&lt;!doctype html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;!{app}&lt;/div&gt;<br>    &lt;script src=&quot;bundle.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>You’ll notice the file is basically the same, save for !{app} being inserted into the HTML. This is a pug variable, which will be later on replaced by the actual HTML.</p><p>Let’s now create our server:</p><pre>// server.js</pre><pre>import React from &#39;react&#39;;<br>import { renderToString } from &#39;react-dom/server&#39;;<br>import express from &#39;express&#39;;<br>import path from &#39;path&#39;;</pre><pre>import App from &#39;./src/App&#39;;</pre><pre>const app = express();<br>app.set(&#39;view engine&#39;, &#39;pug&#39;);<br>app.use(&#39;/&#39;, express.static(path.join(__dirname, &#39;dist&#39;)));</pre><pre>app.get(&#39;*&#39;, (req, res) =&gt; {<br>  const html = renderToString(<br>    &lt;App /&gt;<br>  );</pre><pre>  res.render(path.join(__dirname, &#39;src/index.pug&#39;), {<br>    app: html<br>  });<br>});</pre><pre>app.listen(3000, () =&gt; console.log(&#39;listening on port 3000&#39;));</pre><p>Let’s step through the file.</p><pre>import { renderToString } from &#39;react-dom/server&#39;;</pre><p>react-dom library contains a separate, named export renderToString which works similarly to the render we know, but instead of rendering to the DOM, it renders the HTML as string.</p><pre>const app = express();<br>app.set(&#39;view engine&#39;, &#39;pug&#39;);<br>app.use(&#39;/&#39;, express.static(path.join(__dirname, &#39;dist&#39;)));</pre><p>We’re creating a new express server instance, and letting it know we want to use the pug template engine. We could get away with reading the file and doing a search &amp; replace, but that’s really ineffective and can cause issues with multiple access to the file system or caching issues.</p><p>In the last line, we’re instructing express to look for file in the dist folder, and if a request (e.g. /bundle.js) matches a file, that is present in that folder, reply with it.</p><pre>app.get(&#39;*&#39;, (req, res) =&gt; {<br>});</pre><p>Now in turn we ask express to add a handler for any unmatched URL — this includes our non-existing index.html file (remember, we renamed it to index.pug and also it’s not available in the dist folder).</p><pre>const html = renderToString(<br>  &lt;App /&gt;<br>);</pre><p>Using renderToString we render our application. This code looks exactly like our entry point, but it does not have to.</p><pre>res.render(path.join(__dirname, &#39;src/index.pug&#39;), {<br>  app: html<br>});</pre><p>Once we have the rendered HTML, we tell express to respond by rendering the index.pug file, and replacing the app variable, with the HTML we received.</p><pre>app.listen(3000, () =&gt; console.log(&#39;listening on port 3000&#39;));</pre><p>Last part is actually starting the server, and making it listen on port 3000.</p><p>All that’s left to do is to add a proper script topackage.json:</p><pre>&quot;scripts&quot;: {<br>  &quot;server&quot;: &quot;babel-node server.js&quot;<br>}</pre><p>Now, once we call yarn run server we should receive a confirmation, that the server is indeed running. Navigate your browser to <a href="http://localhost:3000/">http://localhost:300</a>0 where you should again see your application. But this time if you view the source you should see:</p><pre>&lt;!doctype html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;div data-reactroot=&quot;&quot;&gt;Welcome to SSR powered React application!&lt;/div&gt;&lt;/div&gt;<br>    &lt;script src=&quot;bundle.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>If that is the case, it means that server-side rendering is working as expected, and you can start to grow your application!</p><h4>Why do we still need bundle.js?</h4><p>In case of our super-simple application, inclusion of bundle.js is not needed — without it, our application would still work. But in case of real-life applications, you’d still want to include the file.</p><p>This allows the browsers that know how to handle JavaScript to take over and perform the future interaction with your page on the client side, and those that do not know how to parse JS to navigate the page with the actual HTML returned by the server.</p><h4>Things to keep in mind</h4><p>While SSR might look simple enough, when developing the application you need to watch out for some topics, which might not be initially clear:</p><ul><li>any state generated on the server side will not be passed to the client application state; that means that if your backend fetches some data and uses it to render HTML, it will not be placed in the this.state that the browser sees</li><li>componentDidMount is not called on the server — this means that none of your data-fetching that you’re used to place there will not be called; this is generally a good thing, as you should be providing the data as props if you need it. Remember that you need to delay your render (calling res.render) until the data is fetched, which might introduce some delay for your visitors</li><li>if you’re using a react router (e.g. <a href="https://reach.tech/router/server-rendering">@reach/router</a> or <a href="https://reacttraining.com/react-router/web/guides/server-rendering">react-router</a>) you need to make sure that the proper URL is passed to the application when it’s rendered on the server — be sure to check the proper documentation!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb42dc059b38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React — React 16.3 + Component life-cycle]]></title>
            <link>https://medium.com/@baphemot/understanding-react-react-16-3-component-life-cycle-23129bc7a705?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/23129bc7a705</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Thu, 19 Apr 2018 18:26:26 GMT</pubDate>
            <atom:updated>2018-04-20T03:23:11.838Z</atom:updated>
            <content:encoded><![CDATA[<p>The release of 16.3 introduced some new life-cycle functions, which replace existing ones to provide better support for the new asynchronous nature of React.</p><p>This article is an update on <a href="https://medium.com/@baphemot/understanding-reactjs-component-life-cycle-823a640b3e8d">the previous one</a>, which talked about the “old” lifecycle, thus it’s not going to focus on all of the lifecycles, only the new ones.</p><h3>static getDerivedStateFromProps(nextProps, prevState)</h3><p>The new function which main responsibility is ensuring that the state and props are in sync for when it is required. It’s main job is replacing <em>componentWillReceiveProps</em></p><p>gDSFP is a static function and as such has no access to this — you are instead expected to return an object, which will be merged into the future state of the component (exactly like working with setState!)</p><p>The function is used when a component is updated but also when it is mounted, right after the constructor was called, so you no longer need to use constructor or class property form of state if you want to set initial state from props.</p><h3>getSnapshotBeforeUpdate(prevProps, prevState)</h3><p>Other of the two new functions, invoked in the so called “pre-commit phase”, right before the changes from VDOM are to be reflected in the DOM.</p><p>It is usable mostly if you need to read the current DOM state, for example you have an application in which new messages are added to the top of the screen — if a user scrolled down, and a new message is added the screen could move and make the UI harder to use. By adding getSnapshotBeforeUpdate you can calculate current scroll position and maintain it through the DOM update.</p><p>Even though the function is not static, it is recommended to return the value, not update the component. The returned value will be passed to componentDidUpdate as the 3rd parameter.</p><h3>Deprecated functions</h3><p>While the new functions are there to make your transition to AsyncMode easier, you are not forced to migrate all your code. The following functions will be marked as deprecated and in later releases renamed:</p><ul><li>componentWillReceiveProps — UNSAFE_componentWillReceiveProps</li><li>componentWillUpdate — UNSAFE_componentWillUpdate</li></ul><p>You will start seeing the deprecation warnings in next major version, and the function will be removed (the renamed versions will be kept!) in version 17.0</p><p><a href="https://twitter.com/dan_abramov/status/981712092611989509">Dan Abramov</a> summarized the whole change in one image for your pleasure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OoDfQ7pzAqg6yETH." /><figcaption>Summary of the new life-cycle</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23129bc7a705" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React “Suspense”]]></title>
            <link>https://medium.com/@baphemot/understanding-react-suspense-1c73b4b0b1e6?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c73b4b0b1e6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[suspense]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Wed, 07 Mar 2018 06:45:35 GMT</pubDate>
            <atom:updated>2018-03-07T09:11:51.143Z</atom:updated>
            <content:encoded><![CDATA[<p>At the stage of last JSConf.is conference, Dan Abramov unveiled a new feature / API for React called React Suspense. In case you missed it, you can re-watch the talk on YouTube:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fv6iR3Zk4oDY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dv6iR3Zk4oDY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fv6iR3Zk4oDY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8622a6715cf68441d72955827501c74c/href">https://medium.com/media/8622a6715cf68441d72955827501c74c/href</a></iframe><p>In short: the new feature allows you to defer rendering part of your application tree until some condition is met (for example data from an endpoint or a resource is loaded).</p><h3>Why do we need this?</h3><p>Delaying displaying content is possible already, all one has to do is check if the data is loaded, and if not, show a spinner — if it’s as simple as that why do we need this?</p><p>In reality things are a bit more complicated than that:</p><ul><li>with this approach we need to either implement the loading screen in the component which requests / consumes the data, or expose its API to parent</li><li>things get more complicated the more content we need to load (what if you wanted to load a movie details page only when the reviews and all images are also already loaded?)</li><li>once we start making use of AsyncMode things will get even more complex — parts of your application might have new data, parts of it old, which would lead to “tearing” or “flickering” of content</li></ul><p>In order to fix those, and probably more issues which will become more apparent once AsyncMode becomes mainstream React team proposed the new API.</p><p>Another big issue that this solution aims to address is the user experience difference between users with fast device/network and slow ones. If we do go with the spinner that was our initial idea, we might end up showing it for a fraction of a second for users that have fast connection, in which case not showing it at all would be better UX as it eliminates screen flickering.</p><h3>Live demo</h3><p>I’ve been able to <a href="https://codesandbox.io/s/8nq4w3jj39">create a simple demo</a> of the feature (with help from Dan and Aweary over at <a href="https://twitter.com/btmpl/status/971081623948222464">Twitter</a>) so before we jump into the code you might want to check it out.</p><h3>Disclaimer</h3><h4>Please note that the current API is not final and will more than likely change before public release.</h4><h3>Let’s step through the code</h3><p>Most of the code should be easy to follow (remember to also check the comments :)) but there are some things created just for Dan’s demo or introduced in the alpha of React.</p><h4>Resource fetcher / cache provider / “abstractor of the API”:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFn2Od_z_mrb-rqCxkPCKw.png" /><figcaption>A simple cache provider</figcaption></figure><p>The two functions you see here are provided by <a href="https://github.com/acdlite/react/tree/suspense/packages/simple-cache-provider">simple-cache-provider</a> package created by Andrew. Here’s what exactly it’s doing:</p><ol><li>create a shared cache object</li><li>create a “resource fetcher” (createResource) which you call with a set of parameters</li><li>return a promise that will resolve after a set time, with the input value</li></ol><p>This is a really simple example, which in a real-world app would probably be replaced by an API call or similar mechanism. The most important part is that the readText function which once called, will either directly return the value it resolves to (not the Promise!) or would <strong>throw</strong> a Promise.</p><h4>Wait — what?</h4><p><a href="https://twitter.com/sebmarkbage/status/941163837625057280">Yes, you read that right</a>, the function either returns the value, or throws — so you can do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWzWPN9nNCxkrK_26yJdiQ.png" /><figcaption>Simple AsyncText component that resolves to text prop after set time</figcaption></figure><p>The call to readText will either <strong>resolve to the Promise value</strong> or will end up <strong>throwing the Promise</strong>.</p><p>Since this is not apparent (it’s hidden inside simple-cache-provider), you can imagine another version of the AsyncText component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oApf_BSRURHN020FuMGbFg.png" /><figcaption>Alternative to the simple-cache-provider mechanism. Courtesy of <a href="https://medium.com/u/83e2d55aa82f">Alex Krolick</a></figcaption></figure><p>As we know, a React Component can only return JSX (or null) — so we need a method of communicating that we’re “not yet ready” to any parent that is prepared to handle that status. Sounds a bit familiar? If it does, that’s because React already has a mechanism that allows you to throw in a component and let its parent or grand-parent handle this — Error Boundaries. Suspense is reusing some of this API for its own purposes.</p><h4>Using the component</h4><p>If we were to use the component right away, React would warn us that we’re “doing it wrong”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*5sUgYlr23Vdg7izmc0v4_w.png" /><figcaption>Error caused by using an async component.</figcaption></figure><p>In order to properly render the component, we need to import a new React primitive component and create a helper for it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3omn_oXRZMO1bLAkjHw5g.png" /><figcaption>A Loader custom component making use of Timeout — the new primitive</figcaption></figure><p>We’re using the new Timeout component which accepts two input props:</p><ul><li>ms prop, which indicates the time after which we want to see the fallback content (here passed to the Loader component as prop!)</li><li>children which should be a “function as a child” or “render prop” function; this function will be called with one parameter, which indicates if the specified time elapsed</li></ul><p>Let’s take a dive into what’s actually going on there. When this component gets rendered, React will call the child function right away with a value of false which will allow us to render the child component.</p><p>Once the child component renders, it will try to read the data, find out that it’s not there and throw the promise. At this point React catches the Promise, waits the correct time (provided as ms prop) and runs the function again, this time with true so that we can show the fallback.</p><p>Once the Promise resolves, the function is called yet another time, again with false which end up rendering the correct component.</p><p>We could go without creating this helper and inline it all in our component, but this makes it more reusable and easier to read when actually …</p><h4>Using the components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6Wr8vmKo3uFHNTRHu1jxg.png" /><figcaption>Using our Loader and AsyncText components together</figcaption></figure><p>Putting the components together gets rid of the error from previous sections and allows us to have a placeholder shown while the data is being “fetched”. There’s only one issue though — if we were to simply use setState to toggle the visibility of our component (or render it right away) the placeholder would be shown <strong>right away</strong> — not after the specified time.</p><p>Here we get to the last part of the puzzle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euooxXf_xWP2m_EpDtHzaA.png" /></figure><p>ReactDOM.unstable_deferredUpdates is a callback which was introduced back in initial React Fiber release (so 16.0) which allows you to schedule an update with low priority. This is the part that actually allows the Timeout component to “wait” before re-rendering itself.</p><h3>What to expect?</h3><p>A week before Dan’s talk, Andrew <a href="https://twitter.com/acdlite/status/967244380401631232">Tweeted</a> the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*bl1CyRdgvhgh9difD_IJyQ.png" /><figcaption>Screenshot of Andre’s tweet</figcaption></figure><p>Was he right? I think it was. This addition to React tool-set helps us solve a lot of problems we are facing today such as:</p><ul><li>data fetching, without locking the UI and at the same time allowing users to change their decision while data is being fetched (which could result in race conditions)</li><li>providing good experience to users with low-end, high-latency devices</li><li>creating a common abstraction over “loading” state</li></ul><p>Once the API gets finalized, we will probably see a lot of libraries pioneering the solution and will have to adjust our best practices (suddenly calling AJAX requests inside <strong>render</strong> will become OK) but I believe this will allow us all to create even better applications and experience for users!</p><h4>Please note that the current API is not final and will more than likely change before public release.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c73b4b0b1e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s new in React 16.3(.0-alpha)]]></title>
            <link>https://medium.com/@baphemot/whats-new-in-react-16-3-d2c9b7b6193b?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2c9b7b6193b</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Sun, 04 Feb 2018 18:50:24 GMT</pubDate>
            <atom:updated>2018-03-15T16:36:11.271Z</atom:updated>
            <content:encoded><![CDATA[<p>React 16.3-alpha <a href="https://twitter.com/brian_d_vaughn/status/959535914480357376">just hit npmjs</a> and can be downloaded and added to your project. What are the biggest, most interesting changes?</p><blockquote>Update 05.02.2018 — I’ve previously made some wrong observation about the createContext behavior, this section was updated to reflect the actual behavior of the factory function.</blockquote><h3>New context API</h3><p>Context API was always a thing of mystery — it’s an official, documented React API but at the same time developers warned us not to use it because the API might change with time, and it was missing some documentation on purpose. Well, that time is now — the <a href="https://github.com/reactjs/rfcs/blob/master/text/0002-new-version-of-context.md">RFC phase</a> has passed and the new API is merged. It is definitely more “user friendly” and might make your life a bit easier when all you want is simple state management without the “overhead” of Redux or MobX.</p><p>The new API is accessible as React.createContext() and creates two components for us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*HgQMzO2N59Z20NeK5ACGzQ.png" /><figcaption>Creation of the new context via React.createContext</figcaption></figure><p>Calling the factory function will return us an object that has a “Provider” and a “Consumer” in it.</p><p>The “Provider” is a special component which aims to provide data to all components in its sub-tree, so one example of usage would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*R5GQSLcfedGZiTyoSRDVsg.png" /><figcaption>Usage of the new context API — Context.Provider</figcaption></figure><p>Here we select a sub-tree (in this case, the whole tree) to which we want to pass our “theme” context, and set the value we want to pass. The value can of course be dynamic (e.g. based on this.state).</p><p>Next step is to use the Consumer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*XhcIeUaD1G1rpV0c8MYZvA.png" /><figcaption>Usage of the new context API — Context.Consumer</figcaption></figure><p>If you happen to render the “Consumer” without embeding it in a corresponding “Provider”, the default value declared at createContext call will be used.</p><p>Please notice some things:</p><ul><li>the consumer must have access to the same Context component — if you were to create a new context, with the same parameter as input, a new Context would be created and the data would not be passed. For this reason please consider Context a component — it should be created once and then exported + imported whenever needed</li><li>the new syntax uses the function as child (sometime called render prop) pattern — if you’re not familiar with this pattern I recommend reading <a href="https://medium.com/merrickchristensen/function-as-child-components-5f3920a9ace9">some articles on it</a></li><li>it is no longer required to use prop-types to specify contextProps if you want to make use of the new Context API</li></ul><p>The data from the context passed to the function matches the value prop set in the providers Context.Provider component, and altering the data in the Provider will cause all consumers to re-render.</p><h3>New life-cycle methods</h3><p>The other <a href="https://github.com/reactjs/rfcs/blob/master/text/0006-static-lifecycle-methods.md">RFC</a> to make it into the alpha release concerns deprecation of some life-cycle methods and introduction of one (four) new.</p><p>This change aims to enforce best practices (you can read up on why those functions can be tricky in <a href="https://medium.com/@baphemot/understanding-reactjs-component-life-cycle-823a640b3e8d">my article on life-cycle methods)</a> which will be very crucial once the asynchronous rendering mode (which was one of React 16 “Fiber” main goals) will be fully activated.</p><p>The functions that will be in time considered deprecation are:</p><ul><li>componentWillMount — please use componentDidMount instead</li><li>componentWillUpdate — please use componentDidUpdate instead</li><li>componentWillReceiveProps — a new function, static getDerivedStateFromProps is introduced</li></ul><p>Do not be alarmed, you are still able to use those functions — the depracation notices are slotted for 16.4 and removal of them is planned in 17.0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*x-Sf7tN3BNWuL4SWMGyFTg.png" /><figcaption>Everyone panics. Dan says not to panic. Some people still panic.</figcaption></figure><p>You will only see the deprecation notices if you also opt in into the new StrictMode or AsyncMode in which case you can still suppress them by using:</p><ul><li>UNSAFE_componentWillMount</li><li>UNSAFE_componentWillReceiveProps</li><li>UNSAFE_componentWillUpdate</li></ul><h3>static getDerivedStateFromProps</h3><p>As componentWillReceiveProps gets removed, we need some means of updating the state based on props change — the community decided to introduce a new — <strong>static</strong> — method to handle this.</p><p>What’s a static method? A static method is a method / function that exists on the <strong>class</strong> not its instance. The easiest difference to think about is that <strong>static</strong> method does not have access to this and has the keyword static in front of it.</p><p>Ok, but if the function has no access to this how are we to call this.setState? The answer is — we don’t. Instead the function should return the updated state data, or null if no update is needed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*iIRN5UAvsf-6d84NweGlzQ.png" /><figcaption>Using getDerivedStateFromProps in order to update state</figcaption></figure><p>The returned value behaves similarly to current setState value — you only need to return the part of state that changes, all other values will be preserved.</p><h4>Things to keep in mind:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*xGRcRf9KyVNEm4r_Wt9UMw.png" /><figcaption>Remember to init state!</figcaption></figure><p>You still need to declare the initial state of the component (either in constructor or as a class field).</p><p>getDerivedStateFromProps is called both on initial mounting and on re-rendering of the component, so you can use it instead of creating state based on props in constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*Wv-6Yyg7Wd5gIIBu2IKH7w.png" /><figcaption>Error, please use just getDerivedStateFromProps</figcaption></figure><p>If you declare both getDerivedStateFromProps and componentWillReceiveProps only getDerivedStateFromProps will be called, and you will see a warning in the console.</p><p>Usually, you would use a callback to make sure some code is called when the state was actually updated — in this case, please use componentDidUpdate instead.</p><p>If you prefer not to use the static keyword, you can use the alternative syntax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*nb9hnMETRb8Nc26ogTlX6A.png" /><figcaption>Declare getDerivedStateFromProps without using static</figcaption></figure><h3>StrictMode</h3><p>Strict mode is a new way to make sure your code is following the best practices. It’s a component available under React.StrictMode and can be added to your application tree or subtree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*cT32zSlTdDHMDbNDkpOwdw.png" /><figcaption>Usage of the ‘use strict’ … I mean StrictMode</figcaption></figure><p>If one of the children components, rendered in the StrictMode subtree uses some of the method mentioned in previous paragraphs (like componentWillMount) you will then see an error message in browser console when running an development build:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*etTOl69nI0EmND_D68W7xA.png" /><figcaption>Error: unsafe lifecycle in StrictMode subtree</figcaption></figure><p>Currently the error message <a href="https://fb.me/react-strict-mode-warnings">points</a> to the RFC for the life-cycle methods removal.</p><h3>AsyncMode</h3><p>The not-yet-active async Component support was renamed to be aligned with the StrictMode and is now available under React.unstable_AsyncMode. Using it will also activate StrictMode warnings.</p><p>If you want to learn more about asynchronous components you might check some articles / examples at:</p><ul><li><a href="https://build-mbfootjxoo.now.sh/">https://build-mbfootjxoo.now.sh/</a></li><li><a href="https://github.com/koba04/react-fiber-resources">https://github.com/koba04/react-fiber-resources</a></li></ul><h3>New version of React Developer Tools</h3><p>Additionally, a new version of the Developer Tools was released to support debugging the new components.</p><p>If you’re using Chrome — you might need to wait a bit more, as it’s not updated yet in the store, and trying to debug results in … interesting results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*VzzTmbTx7dmzll94.png" /><figcaption>React. __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED is still better</figcaption></figure><p>Firefox users should be able to make use of the new features already:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*DN9BX9MC4xDjdXKKAAAf7Q.png" /><figcaption>New AsyncComponent is visible in the Firefox Developer Tools</figcaption></figure><h3>More to come?</h3><p>Please keep in mind that this is an alpha release and the stable 16.3 might have more / fewer changes. That said, according to Dan, 16.3 should be released “sometime next week”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*JE0fFrRpCmzCaG-hVEZWpA.png" /><figcaption>Last’s week next week is this week.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2c9b7b6193b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding CORS]]></title>
            <link>https://medium.com/@baphemot/understanding-cors-18ad6b478e2b?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/18ad6b478e2b</guid>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fetch]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Sat, 27 Jan 2018 16:21:06 GMT</pubDate>
            <atom:updated>2018-02-03T13:41:51.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*AAtbKMYYz5wgxed7Tu6tzw.png" /><figcaption>“OK, but no”</figcaption></figure><p>If you ever worked with an AJAX call, you are probably familiar with the following error displayed in browser console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*U2MpZQXPI-RW2JASIoeaFQ.png" /><figcaption>Failed to load <a href="https://example.com/">https://example.com/</a>: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘<a href="https://anfo.pl&/#39;">https://anfo.pl&#39;</a> is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.</figcaption></figure><p>If you see this message it means the response failed yet you are still able to see the returned data if you go to the Network tab — what’s the idea here?</p><h3>Cross-Origin Resource Sharing (CORS)</h3><p>The behavior you are observing is the effect of browsers CORS implementation.</p><p>Before CORS became standarized there was no way to call an API endpoint under different domain for security reasons. This was (and to some degree still is) blocked by the Same-Origin Policy.</p><p>CORS is a mechanism which aims to allow requests made on behalf of you and at the same time block some requests made by rogue JS and is triggered whenever you are making an HTTP request to:</p><ul><li>a different domain (eg. site at <a href="http://www.example.com/">example.com</a> calls <a href="http://www.api.com)/">api.com)</a></li><li>a different sub domain (eg. site at <a href="http://www.example.com/">example.com</a> calls api.example.com)</li><li>a different port (eg. site at <a href="http://www.example.com/">example.com</a> calls <a href="http://www.example.com:3001)">example.com:3001)</a></li><li>a different protocol (eg. site at <a href="https://example.com/">https://example.com</a> calls <a href="http://example.com)/">http://example.com)</a></li></ul><p>This mechanism prevents attackers that plant scripts on various websites (eg. in ads displayed via Google Ads) to make an AJAX call to <a href="http://www.yourbank.com,/">www.yourbank.com</a> and in case you were logged in making a transaction using *your* credentials.</p><p>If the server does not respond with specific headers to a “simple” GET or POST request — it will still be send, the data still received but the browser will not allow JavaScript to access the response.</p><p>If your browser tries to make a “non simple” request (eg. an request that includes cookies, or which Content-type is other than application/x-ww-form-urlencoded, multipart/form-data or text-plain) an mechanism called <strong>preflight</strong> will be used and an OPTIONS request will be sent to the server.</p><p>An common example of “non simple” request is to add cookies or custom headers — it your browser sends such a request and the server does not respond properly, only the preflight call will be made (without the extra headers) but the actual HTTP request the brower meant to make will not be sent.</p><h3>Access-Control-Allow-What?</h3><p>CORS uses a few HTTP headers — both in request and response — but the ones you must understand in order to be able to continue working are:</p><h4>Access-Control-Allow-Origin</h4><p>This header is meant to be returned by the server, and indicate what client-domains are allowed to access its resources. The value can be:</p><ul><li>* — allow any domain</li><li>a fully qualified domain name (eg. <a href="https://example.com)/">https://example.com)</a></li></ul><p>If you require the client to pass authentication headers (e.g. cookies) the value <strong>can not</strong> be * — it must be a fully qualified domain!</p><h4>Access-Control-Allow-Credentials</h4><p>This header is only required to be present in the response if your server supports authentication via cookies. The only valid value for this case is true.</p><h4>Access-Control-Allow-Headers</h4><p>Provides a comma separated list of request header values the server is willing to support. If you use custom headers (eg. x-authentication-token you need to return it in this ACA header response to OPTIONS call, otherwise the request will be blocked.</p><h4>Access-Control-Expose-Headers</h4><p>Similarly, this response should contain a list of headers that will be present in the actual response to the call and should be made available to the client. All other headers will be restricted.</p><h4>Access-Control-Allow-Methods</h4><p>A comma separated list of HTTP request type verbs (eg. GET, POST) which the server is willing to support.</p><h4>Origin</h4><p>This header is part of the request that the client is making, and will contain the domain from which the application is started. For security reasons browsers will not allow you to overwrite this value.</p><h3>How to fix the CORS “error”?</h3><p>You have to understand that the CORS behavior is <strong>not an error</strong> — it’s a mechanism that’s working as expected in order to protect your users, you, or the site you’re calling.</p><p>Sometimes the lack of proper headers is result of wrong client-side implementation (eg. missing authorization data such as API key).</p><p>There are a few ways to “fix the error” depending on the scenario you’re facing:</p><p><strong>A — I’m developing the frontend and have control of or know the person developing the backend</strong></p><p>This is the best case scenario — you should be able to implement the proper CORS response on the server which you’re calling. If the API is using express for node you can use the simple <a href="https://github.com/expressjs/cors">cors</a> package. If you want to make your site properly secure, consider using a whitelist for the Access-Control-Allow-Origin header.</p><p><strong>B — I’m developing the frontend but have no control of the backend now, I need a temporary solution</strong></p><p>This is the second-best scenario, because it’s just the A one, but with some time constrains. To temporary fix the issue you can make your browser ignore CORS mechanism — for example use the <a href="https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi">ACAO</a> Chrome extension or by disabling it completely by running Chrome with the following flags:</p><pre>chrome --disable-web-security --user-data-dir</pre><p><strong>IMPORTANT</strong> please remember that this will disable the mechanism for <strong>every</strong> website for the duration of your whole browser session. Use with caution.</p><p>Another alternative here is using <a href="https://webpack.js.org/configuration/dev-server/#devserver-proxy">devServer.proxy</a> (assuming you’re using webpack to serve your app) or use a CORS-as-a-service solution such as <a href="https://cors-anywhere.herokuapp.com/">https://cors-anywhere.herokuapp.com/</a></p><p><strong>C — I’m developing the frontend, have no control of the backend and never will</strong></p><p>Ok, now things are getting complicated. First you should probably establish <strong>why</strong> the server is not sending the proper headers.</p><p>Maybe they do not allow 3rd party apps to access their API? Maybe their API is only meant to be consumed by server-side applications and not browsers? Maybe you should be sending an authorization token of sorts in the URL?</p><p>If you still think you should be able to access the data via browser, you will have to write your own proxy that will sit between the browser application and the API, similarly to how we did it in solution B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*5ceGGBjNyh3qIlnSB0hDlw.png" /><figcaption>Adding a proxy in the middle</figcaption></figure><p>The proxy does not have to be running on the same domain as your application, as long as the proxy itself properly supports CORS when communicating with the client. The communication between proxy and the API does not have to support CORS at all.</p><p>You can either write your own platform, or use a ready made solution such as <a href="https://www.npmjs.com/package/cors-anywhere">https://www.npmjs.com/package/cors-anywhere</a></p><p>Remember that such approach can introduce a security risk if you want to support credentials.</p><h3>More about CORS</h3><p>If you wish to learn more about CORS details I recommend checking out the detailed <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">MDN article</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18ad6b478e2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React — Component life-cycle]]></title>
            <link>https://medium.com/@baphemot/understanding-reactjs-component-life-cycle-823a640b3e8d?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/823a640b3e8d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Wed, 06 Sep 2017 18:55:37 GMT</pubDate>
            <atom:updated>2019-01-10T12:42:26.838Z</atom:updated>
            <content:encoded><![CDATA[<p>React provides developers with many methods or “hooks” that are called during the life-cycle of an component, which allows us to update the UI and application state. Knowing when to use which of them is crucial to properly understanding how to work with React.</p><h3>Update:</h3><p>React 16.3 introduced two more life-cycle methods and depracated few of them, be sure to check up the follow-up at <a href="https://medium.com/@baphemot/understanding-react-react-16-3-component-life-cycle-23129bc7a705">https://medium.com/@baphemot/understanding-react-react-16-3-component-life-cycle-23129bc7a705</a></p><h3>constructor</h3><p>constructors are the basic of OOP — this is a special function that will get called whenever a new object is created. It’s very important to call a special function super in cases where our class extends any other class that also has a defined constructor. Calling this special function will call the constructor of our parent class and allow it to initialize itself. This is why we have access to this.props only after we’ve initially called super.</p><p>As mentioned, constructors are perfect for setting up our Component — create any fields (variables starting with this.) or initialize state based on props received.</p><p>This is also the only place where you are expected to change / set the state by directly overwriting the this.state fields. In all other instances remember to use this.setState</p><p><strong>DO</strong></p><ul><li>set initial state</li><li>if not using class properties syntax — prepare all class fields and bind functions that will be passed as callbacks</li></ul><p><strong>DON’T</strong></p><ul><li>cause any side effects (AJAX calls etc.)</li></ul><h3>deprecated — componentWillMount</h3><p>This is a somehow special case — componentWillMount does not differ much from constructor - it is also called once only in the initial mounting life-cycle. Historically there were some reasons to use componentWillMountover constructor <a href="https://github.com/reactjs/react-redux/issues/129">see this react-redux issue</a> but please keep in mind that the practice described there is since deprecated.</p><p>Many will be tempted to use this function in order to send a request to fetch data and expect the data to be available before the initial render is ready. This is not the case — while the request will be initialized before the render, it will not be able to finish before the render is called.</p><p>Additionally, with the changes to React Fiber (post React 16 beta release) this function might end up being called multiple times before the initial render is called so might result in triggering multiple side-effects. Due to this fact it is <strong>not</strong> recommended to use this function for any side-effect causing operations.</p><p>It is important to note that this function is called when using server-side-rendering while it counterpart — componentDidMount will not be called on the server but on the client in such case. So if some side-effect <em>is</em>desired on the server part this function should be used as an exception.</p><p>A setState used in this function is “free” and will not trigger a re-render.</p><p><strong>DO</strong></p><ul><li>update state via this.setState</li><li>perform last minute optimization</li><li>cause side-effects (AJAX calls etc.) <strong>in case of server-side-rendering only</strong></li></ul><p><strong>DON’T</strong></p><ul><li>cause any side effects (AJAX calls etc.) on client side</li></ul><h3>deprecated — componentWillReceiveProps(nextProps)</h3><p>This function will be called in each update life-cycle caused by changes to props (parent component re-rendering) and will be passed an object map of all the props passed, no matter if the prop value has changed or not since previous re-render phase.</p><p>This function is ideal if you have a component whose parts of state are depending on props passed from parent component as calling this.setState here will not cause an extra render call.</p><p>Please keep in mind that due to the fact that the function is called with all props, even those that did not change it is expected the developers implement a check to determine if the actual value has changed, for example:</p><pre>componentWillReceiveProps(nextProps) {<br>  <strong>if</strong>(nextProps.myProp !== <strong>this</strong>.props.myProps) {<br>    // nextProps.myProp has a different value than our current prop<br>    // so we can perform some calculations based on the new value<br>  }<br>}</pre><p>Due to the fact that with React Fiber (post 16 beta) this function might be called multiple times before the renderfunction is actually called it is <strong>not</strong> recommended to use any side-effect causing operations here.</p><p><strong>DO</strong></p><ul><li>sync state to props</li></ul><p><strong>DON’T</strong></p><ul><li>cause any side effects (AJAX calls etc.)</li></ul><h3>shouldComponentUpdate(nextProps, nextState, nextContext)</h3><p>By default, all class based Components will re-render themselves whenever the props they receiver, their state or context changes. If re-rendering the component is computation heavy (e.g. generating a chart) or is not recommended for some performance reasons, the developer is given access to a special function which will be called in the update cycle.</p><p>This function will be called internally with next values of props, state and object. Developer can use those to verify that the change requires a re-render or not and return false to prevent the re-rendering from happening. In other case, you are expected to return true.</p><p><strong>DO</strong></p><ul><li>use for increasing performance of poor performing Components</li></ul><p><strong>DON’T</strong></p><ul><li>cause any side effects (AJAX calls etc.)</li><li>call this.setState</li></ul><h3>deprecated — componentWillUpdate(nextProps, nextState)</h3><p>If the shouldComponentUpdate function is not implemented, or it decided that the component should update in this render cycle, another life-cycle function will be called. This function is commonly used to perform state and props synchronization for when parts of your state are based on props.</p><p>In cases where shouldComponentUpdate is implemented, this function can be used instead of componentWillReceiveProps as it will be called only when the component will actually be re-rendered.</p><p>Similarly to all other componentWill* functions, this function might end up called multiple times before render so it it <strong>not</strong> advised to perform side-effects causing operations here.</p><p><strong>DO</strong></p><ul><li>synchronize state to props</li></ul><p><strong>DON’T</strong></p><ul><li>cause any side effects (AJAX calls etc.)</li></ul><h3>componentDidUpdate(prevProps, prevState, prevContext)</h3><p>This function will be called after render is finished in each of the re-render cycles. This means that you can be sure that the component and all its sub-components have properly rendered itself.</p><p>Due to the fact that this is the only function that is guaranteed to be called only once in each re-render cycle it is recommended to use this function for any side-effect causing operations. Similarly to componentWillUpdateand componentWillReceiveProps this function is called with object-maps of <strong>previous</strong> props, state and context, even if no actual change happened to those values. Because of that developers are expected to manually check if given value changed and only then perform various update operations:</p><pre>componentDidUpdate(prevProps) {<br>  if(prevProps.myProps !== this.props.myProp) {<br>    // this.props.myProp has a different value<br>    // we can perform any operations that would <br>    // need the new value <strong>and</strong>/<strong>or</strong> cause side-effects <br>    // like AJAX calls with the new value - this.props.myProp<br>  }<br>}</pre><p><strong>DO</strong></p><ul><li>cause side effects (AJAX calls etc.)</li></ul><p><strong>DON’T</strong></p><ul><li>call this.setState as it will result in a re-render</li></ul><p>An exception to the above rule is updating the state based on some DOM property which can be only computed once a component has re-rendered (e.g. position / dimensions of some DOM nodes). Please take extra care to prevent against updating if the value did not in fact change as it might result in a render loop.</p><h3>componentDidCatch(errorString, errorInfo)</h3><p>A new addition in React 16 — this life-cycle method is special in way that it can react to events happening in the child component, specifically to any uncaught errors happening in any of the child components.</p><p>With this addition you can make your parent-element handle the error by — for example — setting the error info in state and returning appropriate message in its render, or logging to reporting system, e.g.:</p><pre>componentDidCatch(errorString, errorInfo) {<br>  this.<strong>setState</strong>({<br>    <strong>error</strong>: errorString<br>  });<br>  ErrorLoggingTool.<strong>log</strong>(errorInfo);<br>}</pre><pre><strong>render</strong>() {<br>  <strong>if</strong>(this.state.<strong>error</strong>) <strong>return</strong> &lt;ShowErrorMessage <strong>error</strong>={this.state.<strong>error</strong>} /&gt;<br>  <strong>return</strong> (<br>    // render normal component output<br>  );<br>}</pre><p>When an error happens, the function will be called with:</p><ul><li>errorString — the .toString() message of the error</li><li>errorInfo — an object with a single field componentStack which represent the stack trace back to where the error occured, e.g.:</li></ul><pre>in Thrower<br>    in div (created <strong>by</strong> App)<br>    in App</pre><h3>componentDidMount</h3><p>This function will be called only once in the whole life-cycle of a given component and it being called signalizes that the component — and all its sub-components — rendered properly.</p><p>Since this function is guaranteed to be called only once it is a perfect candidate for performing any side-effect causing operations such as AJAX requests.</p><p><strong>DO</strong></p><ul><li>cause side effects (AJAX calls etc.)</li></ul><p><strong>DON’T</strong></p><ul><li>call this.setState as it will result in a re-render</li></ul><p>An exception to the above rule is updating the state based on some DOM property which can be only computed once a component has re-rendered (e.g. position / dimensions of some DOM nodes). Please take extra care to prevent against updating if the value did not in fact change as it might result in a render loop.</p><h3>componentWillUnmount</h3><p>Use this function to “clean up” after the component if it takes advantage of timers (setTimeout, setInterval), opens sockets or performs any operations we need to close / remove when no longer needed.</p><p><strong>DO</strong></p><ul><li>remove any timers or listeners created in lifespan of the component</li></ul><p><strong>DON’T</strong></p><ul><li>call this.setState, start new listeners or timers</li></ul><h3>Component cycles</h3><p>There are multiple reasons a component might re-render, and in each of them different functions are called allowing the developer to update certain parts of the Component.</p><p><strong>Component creation</strong></p><p>The first cycle is the creation for component, which usually happens the first time a component is encountered in the parsed JSX tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*A-w6Gd0DdgqkhF-jstYoTg.png" /></figure><p><strong>Component re-rendering due to re-rendering of the parent component</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*DNNTps27uJ_YmhZZqClxAw.png" /></figure><p><strong>Component re-rendering due to internal change (e.g. a call to </strong><strong>this.setState())</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*VwTaOozcyavpmBoLBbY9RA.png" /></figure><p><strong>Component re-rendering due to call to </strong><strong>this.forceUpdate</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*herMU9doYvK-nQaqTPM6lQ.png" /></figure><p><strong>Component re-rendering due to catching an error</strong></p><p>Introduced in React 16 as “ErrorBoundaries”. A component can define a special layer which can catch errors and provide a new life-cycle method — componentDidCatch - which allows developers to provide self-repair actions for recovery or graceful handling of errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*FS-CKtFsDPZ8L1FWfx5MWg.png" /></figure><p>Shoutout to <a href="https://twitter.com/james_k_nelson">@James_k_nelson</a>, who just recently published a componentWillReceiveProps simulator, which you can find and play with at <a href="https://reactarmory.com/guides/lifecycle-simulators">https://reactarmory.com/guides/lifecycle-simulators</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=823a640b3e8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ReactJS — data hydration / initialization]]></title>
            <link>https://medium.com/@baphemot/understanding-reactjs-data-hydration-initialization-bacbb790c7cb?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bacbb790c7cb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Wed, 23 Aug 2017 10:38:59 GMT</pubDate>
            <atom:updated>2018-02-09T18:13:59.042Z</atom:updated>
            <content:encoded><![CDATA[<p>At times you might want to have some information available to your application from outside sources — maybe you’re embedding your application in some bigger website and want to access data that is already present (for example data of authorized user).</p><p>Passing data to the application at run time is known as “initialization”, “bootstrapping” or “state hydration”. Lets go through couple of solutions.</p><h4>Important:</h4><blockquote>Please note that allowing data from outside of your application to be accessed inside of React might open you to attacks such as XSS or CSRF. Please make sure all the data you are accessing in React comes from a trusted source.</blockquote><blockquote>While you do not need to use any special functions to escape characters, you should be very careful if you will be using<strong> </strong>dangerouslySetInnerHtml<strong><em>.</em></strong></blockquote><h3>A — make a API call</h3><p>The first solution assumes the data you are looking for is available by calling a API, which might be ideal when the response you expect will be the same for all of your users.</p><p>In order to get the data you can make an AJAX call (for example by using <a href="https://github.com/mzabriskie/axios">axios</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch</a>).</p><p>Pros:</p><ul><li>secure — very unlikely that an attacker would be able to inject malicious code</li></ul><p>Cons:</p><ul><li>performs an additional HTTP request which adds to load time</li><li>unless already authorized, can’t be used to fetch personalized response; authorization adds the overhead of yet another request</li></ul><h3>B — pass data via window object</h3><p>When the data is already available to the backend (for example the user is already authorized, or set of images to display in your React widget is known) you can assign the data to window object and then read it in React application.</p><p>First lets make changes to our application:</p><pre>class User extends React.Component {<br>  contructor() {<br>    super();<br>    if(window.reactApp) {<br>      this.state = { user: window.reactApp.user };<br>    }<br>    else this.state = { user: undefined };<br>  }<br>}</pre><p>Now we can embed the application:</p><pre>&lt;div id=&quot;react&quot;&gt;&lt;/div&gt;<br>&lt;script&gt;<br>  window.reactApp = {<br>    user: {<br>      name: &#39;BTM&#39;,<br>      email: &#39;example@example.com&#39;<br>    }<br>  }<br>&lt;/script&gt;<br>&lt;script src=&quot;react-application.js&quot;&gt;&lt;/script&gt;</pre><p>Pros:</p><ul><li>data provided to React can be tailored to authorized user or generic on the backend side</li><li>no additional requests needed</li></ul><p>Cons:</p><ul><li>our application relies on the data provided from outside of React context, making it less reusable</li><li>possibility of attackers manipulating the data via XSS/CSRF</li><li>in case we want to embed multiple applications on the same page we would need to make each application use different window.reactApp variable if need to have different input data</li></ul><h3>C — pass data via attribute on parent node</h3><p>This is basically a modified version of the example described above, but instead of storing the data in window global object, we are going to store it as a data-attribute on the node into which React will render.</p><p>This time let us start by changing the HTML:</p><pre>&lt;div id=&quot;react&quot; data-react=&#39;{&quot;user&quot;:{&quot;name&quot;:&quot;BTM&quot;,&quot;email&quot;:&quot;<a href="/service/mailto:example@example.com">example@example.com</a>&quot;}}&#39;&gt;&lt;/div&gt;<br>&lt;script src=&quot;react-application.js&quot;&gt;&lt;/script&gt;</pre><p>Now we can change our application:</p><pre>const node = document.getElementById(&#39;root&#39;);<br>const userData = node.dataset.react ? JSON.parse(node.dataset.react) : {};<br>ReactDOM.render(&lt;App user={userData.user} /&gt;, node);</pre><p>Pros:</p><ul><li>data provided to React can be tailored to authorized user or generic on the backend side</li><li>no additional requests needed</li><li>we’re no longer polluting the window object</li></ul><p>Cons:</p><ul><li>our application relies on the data provided from outside of React context, making it less reusable</li><li>possibility of attackers manipulating the data via XSS/CSRF</li><li>data needs to be provided as JSON string, which can lead to some issues in both security and data consistency</li></ul><h3>D — exposing the render function to HTML</h3><p>The solutions provided before might very well be enough for most use case, but sometimes you want to be able to not only pass some data at run time but also be able to update it at later time or manually trigger the rendering of your application. In order to do just that we can provide our HTML page access to the rendering mechanism.</p><p>First thing we need to do is create a function that will init our application and expose it via window object (the function on itself would not be available outside of React context due to how Webpack works):</p><pre>function runApplication(data, node) {<br>  ReactDOM.render(&lt;App data={data} /&gt;, node);<br>}</pre><pre>window.runReactApplication = runApplication;</pre><p>Now we can call our application at any given time:</p><pre>&lt;div id=&quot;MyApp&quot;&gt;&lt;/div&gt;<br>&lt;script src=&quot;react-application.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>  window.runReactApplication({<br>    user: { name: &#39;BTM&#39;, email: &#39;example@example.com&#39; }<br>  }, document.querySelector(&#39;#MyApp&#39;));<br>&lt;/script&gt;</pre><p>Now, anytime we call the window.runReactApplication function with new data as first parameter (but the same node as the second one!) our &lt;App /&gt; component will receive new props, just like a normal React life-cycle would do it.</p><p>Pros:</p><ul><li>data provided to React can be tailored to authorized user or generic on the backend side</li><li>no additional requests needed</li><li>data can be updated and app rendered whenever it’s needed</li></ul><p>Cons:</p><ul><li>app <strong>needs</strong> to be initialized from the HTML</li><li>possibility of attackers manipulating the data via XSS/CSRF</li></ul><h3>Conclusion</h3><p>As with all things React — there is no one, definitive answer to the question “how to pass initial data to my application” — you need to pick a solution that works best for your use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bacbb790c7cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to debugging ReactJS applications]]></title>
            <link>https://medium.com/@baphemot/intro-to-debugging-reactjs-applications-67cf7a50b3dd?source=rss-a5f578f5b81a------2</link>
            <guid isPermaLink="false">https://medium.com/p/67cf7a50b3dd</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[Bartosz Szczeciński]]></dc:creator>
            <pubDate>Mon, 10 Jul 2017 11:54:55 GMT</pubDate>
            <atom:updated>2017-07-10T11:54:55.514Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most important things a developer should learn is how to (properly) debug an application in his language of choice. Knowing that not only allows you to easily find sources of errors in your code, but also teaches you about the inner working of the language thus preventing you from making the same error in the future.</p><p>I will cover a couple of techniques and tools you will find useful when developing ReactJS applications. For the sake of this article I will be using Chrome browser, but most of the techniques are universal and the tools exist for different browsers as well.</p><p><em>Please keep in mind that some of the described scenarios assume you have source maps enabled in your build. While debugging an app without sourcemaps enabled is possible it is much harder.</em></p><h4>Step 0 — get to know your browser</h4><p>Most of the tools you need are already available to you, integrated with the browser — I’m talking about the browser’s developer tools. In most cases you can open them by pressing F12 or right clicking and selecting “Inspect”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtInfEp_5QY95BnmalrebA.png" /><figcaption>Chrome developer tools with Dark theme, inspecting Discordapp.com page</figcaption></figure><p>The two most important parts of the Devtools you should be familiar with will be “Console” and “Network”. I will cover those in further sections.</p><h4>Code linting</h4><p>While a linter might not help you debug your application it might prevent you from introducing the error in the first place. If you don’t want to spend time configuring and fine-tuning your <a href="http://eslint.org/">ESLint</a> (I recommend ESLint here as it’s one of the most popular and powerful) you can use the <a href="https://www.npmjs.com/package/eslint-config-react-app">react-app</a> preset.</p><h4>Console — your first and most powerful friend</h4><p>The console window is one of <em>the</em> most important tools at your disposal. Not only does it show all the messages your application is logging using console.log it also shows the majority of error messages in browser caused by your app. On top of that it’s an REPL environment into which you can type any valid JS code and have it executed right away.</p><p>console object in JS has a lot of features — if you want to read up on them I highly recommend the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Console">page over at MDN</a>.</p><p>console is also your “basic” way to debug the application. Want to see if certain part of your code is reached? Is the onClick handler called? What’s the value of that variable? console.log it — in most cases the otput (or lack of it) will allow you to quickly assess what’s wrong with your application.</p><p><strong>Keep in mind</strong>: console.log when used with an object/array as a parameter can be deceiving. Consider the following code:</p><pre>const myObject = { name: &#39;BTM&#39; }<br>console.log(myObject);<br>myObject.name = &#39;John&#39;;</pre><p>What do you expect to see in the output of the log?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*Da21dEwbKFGSJrXH_viDAA.png" /><figcaption>Looks ok, right?</figcaption></figure><p>“Yes, ‘BTM’, just what I thought!” Is it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*FAX1GSUIe5JPwsGOi4cTeg.png" /><figcaption>BTM === John (no, not really …)</figcaption></figure><p>Ok …. what’s going on here? console.log uses the reference when we expand it with the arrow down, but the value in the collapsed version. Keep that in mind when trying to debug React application — it might look like the valid data is passed to a child component while in fact it is being mutated in parent!</p><h4>Network tab</h4><p>There is a very high chance that your application uses some form of communication with a server, and ther ewill be times that you will get wrong data or data will come in a shape you weren’t expecting it. The Network tab is your “go to” here. It will track all HTTP and Websocket requests that happened since you opened the tool (this is sadly not true for Websockets — it will only show communication happening over sockets that were opened <em>after</em> you opened the Developer Tools, so if you need to spy on WS remember to have the tool opened beforehand):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzqWDCSPS48PIDyEkKik5g.png" /><figcaption>A detailed view of an response from Discord</figcaption></figure><p>Important things to keep in mind:</p><ul><li>a general rule-of-thumb is “red requests failed, white requests are OK”</li><li>each request can have multiple states, keep an eye out on “Pending” requests — if the status persists for a longer time, it might mean you mistyped the URL or the backend is having troubles</li><li>when you click on the request a detailed tab will open — “Preview” and “Response” tabs will show your data; if it looks like the data is OK but you can’t parse it in your app, check the “Content-type” in “Headers” tabs — sometimes servers will send you JSON data as text or HTML which can break some tools</li><li>a very common error which results in data being visible in “Network” tab but not accessible to your app is failing the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">CORS protocol</a>. Keep an eye out for errors like this in your “Console” section:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SUhvMjr_5bRDncb2ufHgQ.png" /><figcaption>CORS request failed</figcaption></figure><p>The CORS error is especially tricky as it will show as a successful request (it will be white on the list) and all the data you expect will be there in “Preview” tab. To get around CORS “limitation” you need to either work with the backend provider (in order to allow CORS on the server, or configure it in a way that it can be used by your app) or use a proxy solution (CORS affects <em>only</em> browsers — any proxy written in a server-side language will just ignore it).</p><h4>React Developer Tools</h4><p>A deceivingly small browser extension from Facebook will be your go-to tool when checking if the data and JSX structure is OK. You can either download the extension from the library for your browser or grab the<a href="https://github.com/facebook/react-devtools"> standalone version</a>.</p><p>After installing the extension you will notice an React icon on the iconbar that highlights whenever you visit an React powered site, and you will see another tab added to the browser Developer Tools. When opened you will see a view similar to HTML structure but instead of HTML nodes you will see the current JSX:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unxAs3GfMApB581arWQY-w.png" /><figcaption>Discord Messages component inspected in React Developer Tools</figcaption></figure><p>Clicking on each invidual JSX element will show you its important data: key, ref, its state and props. You can also use the tool to change some of the values (mostly scalar values: booleans, numbers, strings; it does not support changing objects on the fly).</p><p>You can use the “Search” box to look up your components by their name but another feature is the automatic lookup of an element you right clicked and selected “Inspect” on (all you have to do is change from “Elements” to “React” tab).</p><p>One of the most important features however lies in the update that React Developer Tools adds to the default “Console” window (if you don’t see it when on the “React” tab, click the three-dots icon and select “Show console drawer”). When an React element is selected you can use $r in the console which will give you this of the selected element:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87iiFbNPK0mdTR_4le3vNA.png" /><figcaption>$r = this</figcaption></figure><p>You can interact with the element, call its methods and event handlers just like a normal interaction would. This feature allows you to change complex structures we mentioned earlier (e.g. you can select an element, call its $r.setState({message: &#39;Hello world!&#39;}) which will trigger normal reconcilation process.</p><p><strong>Important</strong>: if you’re running a production build, names of components will be obfuscated by default. You can get around that by setting a static variable displayName on the component. You can use <a href="https://github.com/opbeat/babel-plugin-add-react-displayname">babel-plugin-add-react-displayname</a> to simplify the process.</p><h4><strong>Serious debugging — breakpoints</strong></h4><p>Now that we covered all the “easy” things let’s move into the “real world debugging” — working with breakpoints. A <em>breakpoint</em> is an instruction in code which will stop all the execution and fire up a debugger. There are 2 ways of setting up breakpoints that you will find handy:</p><ul><li>adding debugger; to your source code — when the parser encounters this directive, and the Developer Tools are open it will trigger a breakpoint</li><li>finding the point on which we want to break in the Develooper Tools (“Sources” tab) and clicking on the line number — this will add a visual marker and will act exactly the same as above; breakpoints set up this way persist through browser refresh</li></ul><p>When code execution reaches this point you will see that the page is in “paused” state and the Devtool now have some additional options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cki5oRD7yax_6fZoUovGQQ.png" /><figcaption>Breakpoint active</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*BBTd7qfkGJMaLdNo-C7OiQ.png" /></figure><p>The “Sources” panel shows on which breakpoint the code halted (you can have multiple breakpoints in your application at any given time) and the right hand side shows some interesting information about the current application state, most important are:</p><ul><li>the navigation panel on the top — allowing us to resume the application, step backwards / forwards in execution or disable all breakpoints</li><li>the callstack — shows us what functions were called in order to get to the current application state</li><li>scope — shows what variables are available at the current execution point in what scope (local, global, closure) along with their values; you can also change the values at this point, which — when resumed — will be reflected in your application</li><li>the console is now hooked to the application state, you have access to all variables shown in “Scope” — this allows you to change values in code that is in other cases not accessible from window namespace (e.g. you get access to components this).</li></ul><h3>Specific tools</h3><p>While the above described tools will come in handy in any JS / ReactJS application, there are some tools that you might find useful when working with specific issues / libraries, some of which are:</p><h4>why did you update?</h4><p>A small <a href="https://github.com/garbles/why-did-you-update">library</a> that integrates with your components that shows you why a component did re-render; while the main goal is to provide ways to check for potential optimizations, it is generally useful when debugging rendering issues</p><h4>redux-logger</h4><p>Another small <a href="https://github.com/evgenyrodionov/redux-logger">console addition</a>, this time for when you are working with Redux. Main purpose is logging out state changes and actions handled by Redux.</p><h4>redux-devtools</h4><p>A more advanced extension useful when working with Redux. Comes in two flavors — <a href="https://github.com/gaearon/redux-devtools">a library</a> to add to your application and a browser extension. Main selling point of Redux Devtools is the ability to export / import state as a JSON file (so your testers can share the state with developer when reporting bugs) and the “time travel” which allows you to rewind and fast-forward through a history of Redux reducer states.</p><h4>redux-immutable-state-invariant</h4><p>Immutability is one of the main assumptions of Redux, but sometimes a mutation slips through. Adding <a href="https://github.com/leoasis/redux-immutable-state-invariant">this middleware</a> will help you track such errors by providing console messages when such a situation takes place.</p><h4>rubber-duck debugging</h4><p>No really, hear me out on this one.</p><p>Have you ever had a situation where you started to explain a weird bug to a colleague only to have one of those “oh FFS, THIS is what’s wrong” moments? <a href="https://en.wikipedia.org/wiki/Rubber_duck_debugging">There’s a name for that</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*RuCsCi9B-ypVU9XR.jpg" /><figcaption>Credit: <a href="https://en.wikipedia.org/wiki/Rubber_duck_debugging#/media/File:Rubber_duck_assisting_with_debugging.jpg">https://en.wikipedia.org/wiki/Rubber_duck_debugging#/media/File:Rubber_duck_assisting_with_debugging.jpg</a></figcaption></figure><h3>Know of any good tools or techniques?</h3><p>If you know of any good tool or technique that is worth sharing with other React developers, please let me know in the comments bellow :)</p><p>I’d like to thank <a href="http://blog.isquaredsoftware.com/">acemarke</a> for his help while writing this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67cf7a50b3dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>