<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Duncan Leung: Javascript and Front End Development]]></title><description><![CDATA[Read Code, Write Code, Eat Code, Sleep Code.]]></description><link>http://duncanleung.com/</link><generator>Ghost 0.11</generator><lastBuildDate>Fri, 22 Jun 2018 18:19:08 GMT</lastBuildDate><atom:link href="http://duncanleung.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Fixing React Warnings: Synthetic Events in setState()]]></title><description><![CDATA[<h6 id="tldr">TLDR;</h6>

<ul>
<li><a href="https://facebook.github.io/react/docs/react-component.html#setstate"><code>setState()</code></a> is asynchronous.</li>
<li><a href="https://facebook.github.io/react/docs/events.html"><code>SyntheticEvent</code></a> cannot be accessed asynchronously.</li>
</ul>

<h4 id="problemsusingeventtargetwithinsetstate">Problems Using <code>event.target</code> Within <code>setState()</code></h4>

<p>I came across an unexpected console error and warning when attempting to use <code>event.target</code> within <code>setState()</code>.  </p>

<pre><code>Uncaught TypeError: Cannot read property 'value' of null  
</code></pre>

<pre><code>Warning: This synthetic event is reused for performance reasons. If</code></pre>]]></description><link>http://duncanleung.com/fixing-react-warnings-synthetic-events-in-setstate/</link><guid isPermaLink="false">cbd94661-ca13-46fc-b8be-00481a353e7f</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Mon, 14 Aug 2017 14:47:52 GMT</pubDate><content:encoded><![CDATA[<h6 id="tldr">TLDR;</h6>

<ul>
<li><a href="https://facebook.github.io/react/docs/react-component.html#setstate"><code>setState()</code></a> is asynchronous.</li>
<li><a href="https://facebook.github.io/react/docs/events.html"><code>SyntheticEvent</code></a> cannot be accessed asynchronously.</li>
</ul>

<h4 id="problemsusingeventtargetwithinsetstate">Problems Using <code>event.target</code> Within <code>setState()</code></h4>

<p>I came across an unexpected console error and warning when attempting to use <code>event.target</code> within <code>setState()</code>.  </p>

<pre><code>Uncaught TypeError: Cannot read property 'value' of null  
</code></pre>

<pre><code>Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property 'target' on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().  
</code></pre>

<p>An example of the code I was attempting to run was: <br>
<em>(Open up the console and try to run the demo in <strong>preview view</strong> to see the error)</em></p>

<iframe src="https://codesandbox.io/embed/KYP4KQzl?view=editor" style="width:100%; height:900px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>

<p>&nbsp;</p>

<h4 id="reacteventsystemsyntheticevent">React Event System: <code>SyntheticEvent</code></h4>

<p>It turns out React has it's own event system for event handling, using <a href="https://facebook.github.io/react/docs/events.html"><code>SyntheticEvent</code></a>.</p>

<p>React's <code>SyntheticEvent</code> wraps around the browser's native event to provide cross-browser compatibility support. Instead of passing in the native event to React event handlers, an instance of this <code>SyntheticEvent</code> is passed in.</p>

<p>The console warning I encountered occurs because React re-uses the <code>SyntheticEvent</code> object for performance reasons, by pooling the synthetic events all together. Thus, all the properties on <code>event.target</code> are nullified after an event callback is invoked.</p>

<p>Essentially, <strong><code>SyntheticEvent</code> cannot be used asynchronously</strong>, because the event will no longer exist after the event callback has been invoked.</p>

<p>This is a problem, knowing that <a href="http://www.duncanleung.com/avoiding-react-setstate-pitfalls/">React's <code>setState()</code> behavior is asynchronous</a>.</p>

<p>However, what if I want to use <code>event.target</code> within <code>setState()</code>?</p>

<pre><code>  handleChange(e) {
    this.setState((prevState, props) =&gt; {
      return {
        username: e.target.value     // Attempting to use e.target.value
                                     // within setState()
      }
    })
  }

  render() {
    return (
        &lt;input
          type="text"
          value={this.state.username}
          onChange={this.handleChange}
        /&gt;
    )
  }
}
</code></pre>

<h6 id="solution1usereacteventpersist">Solution 1: Use React <code>event.persist()</code></h6>

<p>Using <code>event.target</code> to construct a new state is a common pattern, and React has provided a solution with <a href="https://facebook.github.io/react/docs/events.html#event-pooling"><code>event.persist()</code></a>.</p>

<p>Calling <code>event.persist()</code> on the event removes the synthetic event from the pool and allows references to the event to be retained asynchronously.</p>

<pre><code>  handleChange(e) {
    e.persist();

    this.setState((prevState, props) =&gt; {
      return {
        username: e.target.value
      }
    })
  }
</code></pre>

<p>&nbsp;</p>

<h6 id="solution2cacheeventtarget">Solution 2: Cache <code>event.target</code></h6>

<p>Another solution is to cache the result of <code>event.target</code> within the event handler, and reference this cached value within the <code>setState()</code> callback.</p>

<pre><code>  handleChange(e) {
    let inputValue = e.target.value;  // Cache the value of e.target.value

    this.setState((prevState, props) =&gt; {
      return {
        username: inputValue
      }
    })
  }
</code></pre>]]></content:encoded></item><item><title><![CDATA[Pure render() 'this' Binding Patterns in React]]></title><description><![CDATA[<p>Another React caveat that I have come across, is to <strong>keep the <code>render()</code> method <em>pure</em></strong>.</p>

<p>Let's take a look, specifically relating to patterns on binding the <code>this</code> context for class methods.</p>

<hr>

<h3 id="iquickoverviewonpurerender">I. Quick Overview on Pure <code>render()</code></h3>

<p>The motivation behind keeping the <code>render()</code> method pure is to avoid issues when</p>]]></description><link>http://duncanleung.com/pure-render-this-binding-patterns-react/</link><guid isPermaLink="false">00326353-dee8-47ff-9b4b-be7bde88a61b</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Wed, 02 Aug 2017 16:12:45 GMT</pubDate><content:encoded><![CDATA[<p>Another React caveat that I have come across, is to <strong>keep the <code>render()</code> method <em>pure</em></strong>.</p>

<p>Let's take a look, specifically relating to patterns on binding the <code>this</code> context for class methods.</p>

<hr>

<h3 id="iquickoverviewonpurerender">I. Quick Overview on Pure <code>render()</code></h3>

<p>The motivation behind keeping the <code>render()</code> method pure is to avoid issues when using <a href="https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate"><code>shouldComponentUpdate()</code></a>, and <a href="https://facebook.github.io/react/docs/react-api.html#react.purecomponent"><code>React.PureComponent</code></a>, which work by performing shallow comparison checks.</p>

<p>The guidelines of a pure <code>render()</code> is:</p>

<ul>
<li>The contents of the <code>render()</code> method <strong>should not create new arrays, objects, or functions.</strong>
<ul><li>A new array, object, or function instance within <code>render()</code> will cause the shallow comparison to always fail. The Component will always re-render.</li></ul></li>
<li><strong>That state is not mutated</strong> within <code>setState()</code>.
<ul><li>A mutated state will not create a new state object, causing the shallow comparison to always succeed. The Component will not re-render.</li></ul></li>
</ul>

<p>&nbsp;</p>

<h6 id="sidecommentnecessityofpurerenderpatterns">Side Comment: Necessity of pure <code>render()</code> patterns?:</h6>

<p><em>Pure <code>render()</code> patterns seem to only have benefits if you are utilizing the <code>shouldComponentUpdate()</code> method, or <code>React.PureComponent</code>.</em></p>

<p><em>Pure <code>render()</code> patterns are considered a "nice to have", but they are not mandatory in writing functioning (and for the most part, performant) React apps.</em></p>

<p><em>React will actually handle the performance of most, small, React apps perfectly fine.</em></p>

<p><strong><em>Following a pure <code>render()</code> pattern may provide an easier transition, when <code>shouldComponentUpdate()</code> or <code>React.PureComponent</code> is actually needed.</em></strong></p>

<p><strong><em>In either case, it's good to understand what a pure/non-pure pattern implies in how the code functions. Let's dig in more...</em></strong></p>

<hr>

<h3 id="iithisbindinginreactrender">II. <code>this</code> Binding in React <code>render()</code></h3>

<p>Most of the discussion, around maintaining pure <code>render()</code> methods, is regarding the <code>this</code> context binding within a <code>render()</code> method.</p>

<p>Assume the base case:</p>

<ul>
<li>Form Component with an ES6 class.</li>
<li>State Object, with the property <code>name</code>, and value of <code>Joe</code></li>
<li><code>handleClick()</code> method that <code>console.log(this.state.name)</code>.</li>
<li><code>render()</code> method that just displays the button.</li>
</ul>

<p>&nbsp;</p>

<p>How should we attach <code>handleClick()</code> to the button, with a correctly bound <code>this</code> to the context of the Form Component instance?</p>

<pre><code>class Form extends React.Component {  
  constructor(props) {
    super(props);

    this.state = {
      name: 'Joe'
    }
  }

  handleClick() {
    console.log(this.state.name); // Uncaught TypeError: Cannot read
                                  // property 'state' of null
  }

  render() {
    return (
      &lt;button onClick={this.handleClick()}&gt;  // How to bind 'this'
                                             // to Form Component instance?
        Click Me
      &lt;/button&gt;
    );
  }
}
</code></pre>

<p>&nbsp;</p>

<h6 id="problembindingthis">Problem: Binding <code>this</code></h6>

<p>The problem originates from ES6 classes not automatically binding the, <code>this</code>, context for methods on the class.</p>

<p>Without explicit <code>this</code> binding, when <code>&lt;button&gt; Click Me &lt;/button&gt;</code> is clicked, the <code>this</code> context within the attached event handler, <code>handleClick()</code>, no longer points to the Form Component instance and we get the error: </p>

<pre><code>Uncaught TypeError: Cannot read property 'state' of null  
</code></pre>

<p>&nbsp;</p>

<h6 id="asidewhentopasspropsintosuper">Aside: When to pass <code>props</code> into <code>super()</code>?</h6>

<p>I noticed there were code samples on various blog articles that differ in passing and omitting <code>props</code> into the <code>super()</code> method.</p>

<p>As a standard, the React team <a href="https://facebook.github.io/react/docs/state-and-lifecycle.html#adding-local-state-to-a-class">recommends</a>:</p>

<p><strong><em>"Class components should always call the base constructor with props"</em></strong>.</p>

<p>For the curious minds: Apparently, passing <code>props</code> into <code>super()</code> <strong>allows access to <code>this.props</code> in the <code>constructor()</code>.</strong></p>

<p>Interestingly, if you omit passing <code>props</code> into <code>super()</code>, it does not affect access to <code>this.props</code> outside of the <code>constructor()</code> (ex. <code>render()</code>, <code>componentDidMount()</code>, etc. will still have access to <code>this.props</code>).</p>

<pre><code>// Not recommended, omitting props.
constructor() {  
  super();

  ...
}


// Recommended: Always call the base constructor with props.
constructor(props) {  
  super(props);

  ...
}
</code></pre>

<hr>

<h3 id="iiinonpurerenderpatternsbindingthis">III. Non-Pure <code>render()</code> Patterns - Binding <code>this</code></h3>

<p><strong><em>Note:</em></strong> <em>Most articles and tutorials I've seen commonly use these two non-pure patterns because of the succinct syntax. Using a non-pure pattern is absolutely fine for those situations. Again, most small React apps will perform perfectly fine using these non-pure <code>render()</code> patterns.</em></p>

<p><strong>To reiterate, a pure <code>render()</code> should not create new functions within <code>render()</code>.</strong></p>

<p>The following two non-pure patterns, using <code>.bind</code> and arrow functions, <strong>return a new function every time the Component re-renders</strong>. This will cause problems when trying to utilize <code>shouldComponentUpdate()</code> and <code>React.PurecComponent</code>.</p>

<p>&nbsp;</p>

<h5 id="1callingbindinrendernonpurerenderpattern">1. Calling <code>bind()</code> in <code>render()</code> - Non Pure <code>render()</code> Pattern</h5>

<p>A common solution to resolve <code>this</code> binding context is to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind"><code>bind()</code></a>. This Javascript native method <em>creates a new function</em> that has its <code>this</code> keyword set to the provided context.</p>

<pre><code>class Form extends React.Component {  
  constructor(props) {
    super(props);

    this.state = {
      name: 'Joe'
    }
  }

  handleClick() {
    console.log(this.state.name); // 'this' context in handleClick()
                                  // bound to Form Component instance
  }

  render() {
    return (
      &lt;button onClick={this.handleClick.bind(this)}&gt;  // Binding 'this'
        Click Me
      &lt;/button&gt;
    );
  }
}
</code></pre>

<p>&nbsp;</p>

<h5 id="2arrowfunctionsnonpurerenderpattern">2. Arrow Functions - Non Pure <code>render()</code> Pattern</h5>

<p>Another common solution to resolve <code>this</code> binding context, is to use arrow functions.</p>

<p>However, we are still returning a new instance of <code>handleClick()</code> from the arrow function every time the Component is re-rendered.</p>

<pre><code>class Form  extends React.Component {  
  constructor(props) {
    super(props);

    this.state = {
      name: 'Joe'
    }
  }

  handleClick() {
    console.log(this.state.name); // 'this' context in handleClick()
                                  // bound to Form Component instance
  }

  render() {
    return (
      &lt;button onClick={() =&gt; this.handleClick()}&gt;  // Binding 'this'
        Click Me
      &lt;/button&gt;
    );
  }
}
</code></pre>

<p>&nbsp;</p>

<p><strong>Note:</strong> Using arrow functions in <code>render()</code> is popular because it serves as a <em>"useful"</em> and convenient way to pass in arguments to an event handler. We'll touch on this more below.</p>

<pre><code>class Form  extends React.Component {  
  constructor(props) {
    super(props);

    this.state = {
      name: 'Joe'
    }
  }

  handleClick(name) {
    console.log(name);
  }

  render() {
    return (

      // Binding 'this', and passing in an argument
      &lt;button onClick={() =&gt; this.handleClick(this.state.name)}&gt;
        Click Me
      &lt;/button&gt;
    );
  }
}
</code></pre>

<hr>

<h3 id="ivpurerenderpatternsbindingthis">IV. Pure <code>render()</code> Patterns - Binding <code>this</code></h3>

<p>The following pure <code>render()</code> patterns do not create new function instances within <code>render()</code>, allowing the shallow comparison check to work correctly.</p>

<p>&nbsp;</p>

<h5 id="1callingbindintheconstructorpurerenderpattern">1. Calling <code>bind()</code> in the Constructor - Pure <code>render()</code> Pattern</h5>

<p>This solution still utilizes <code>bind()</code>, however, we assign the context bound function in the constructor of the Component.</p>

<pre><code>class Form extends React.Component {  
  constructor(props) {
    super(props);

    this.state = {
      name: 'Joe'
    }

    this.handleClick = this.handleClick.bind(this);  // Binding 'this'
  }

  handleClick() {
    console.log(this.state.name); // 'this' context in handleClick()
                                  // bound to Form Component instance
  }

  render() {
    return (
      &lt;button onClick={this.handleClick}&gt;
        Click Me
      &lt;/button&gt;
    );
  }
}
</code></pre>

<p>&nbsp;</p>

<h5 id="2arrowfunctionclassmethodpurerenderpattern">2. Arrow Function Class Method- Pure <code>render()</code> Pattern</h5>

<p>This solution takes advantage of a stage-2 experimental feature, <a href="https://babeljs.io/docs/plugins/transform-class-properties/">Arrow Function Class Methods</a>, allowing arrow functions to be used as class methods to preserve the <code>this</code> context of your method.</p>

<p><strong>Note:</strong> Class properties are currently <a href="https://babeljs.io/docs/plugins/preset-stage-2/">stage-2</a> and require an additional Babel plugin. I've included my <code>.babelrc</code>, <code>webpack.config.js</code>, and <code>package.json</code> at the end of the article for reference.</p>

<pre><code>class Form extends React.Component {  
  constructor(props) {
    super(props);

    this.state = {
      name: 'Joe'
    }
  }

  // Arrow Function Method
  handleClick = () =&gt; {
    console.log(this.state.name); // 'this' context in handleClick()
                                  // bound to Form Component instance
  }

  render() {
    return (
      &lt;button onClick={this.handleClick}&gt;
        Click Me
      &lt;/button&gt;
    );
  }
}
</code></pre>

<p>&nbsp;</p>

<h5 id="3autobindingwithreactcreateclasspurerenderpattern">3. Autobinding with <code>React.createClass</code> - Pure <code>render()</code> Pattern</h5>

<p>ES6 Class syntax is the current standard for writing React (the React docs have also switched over to use ES6 Class syntax). However, when using the traditional syntax of <code>React.createClass</code>, the <code>this</code> context of methods in the Component are actually automatically bound.</p>

<pre><code>var Form = React.createClass({  
  getInitialState () {
    return {
      name: 'Joe'  
    };
  },

  handleClick() {
    console.log(this.state.name); // 'this' context in handleClick()
                                  // bound to Form Component instance
  },

  render() {
    return (
      &lt;button onClick={this.handleClick}/&gt;
    );
  }
});
</code></pre>

<hr>

<h3 id="vpassingargumentstomethodsinrender">V. Passing Arguments to Methods in <code>render()</code></h3>

<p>This is an interesting problem - how do you keep the <code>render()</code> method pure, while passing arguments to event handlers?</p>

<h5 id="1nonpurerenderpassingargumentswitharrowfunctions">1. Non Pure <code>render()</code>: Passing Arguments with Arrow Functions</h5>

<p>There's nothing special here. An easy way to pass arguments to a method within <code>render()</code>, is to use arrow functions.</p>

<p>However, this is a non-pure pattern.</p>

<pre><code>class Form  extends React.Component {  
  constructor(props) {
    super(props);

    this.state = {
      name: 'Joe'
    }
  }

  handleClick(name) {
    console.log(name);
  }

  render() {
    return (

      // Binding 'this', and passing in an argument
      &lt;button onClick={() =&gt; this.handleClick(this.state.name)}&gt;
        Click Me
      &lt;/button&gt;
    );
  }
}
</code></pre>

<p>&nbsp;</p>

<h5 id="2purerenderpassingargumentsusingchildcomponents">2. Pure <code>render()</code>: Passing Arguments using Child Components</h5>

<p>The concept of this pattern is to create a separate Component, <code>&lt;Button /&gt;</code> with its own event handler, <code>wrapperHandler()</code>.</p>

<p><code>wrapperHandler()</code> can call the parent's event handler, <code>handleClick()</code>, and pass in any arguments:</p>

<pre><code>// Create a child Component

const Button = props =&gt; {  
  const wrapperHandler = () =&gt; {
    props.handleClick(props.name);  // Pass in arguments to the original
                                  // event handler 'props.handleClick'
  };

  return (
    &lt;button onClick={wrapperHandler}&gt;
      Click Me
    &lt;/button&gt;
  );
};
</code></pre>

<p>With this pattern, we can ensure that the <code>render()</code> method remains pure, and we avoid creating new function instances on each render.</p>

<p>&nbsp;</p>

<p>In the parent Component, we render an instance of the <code>&lt;Button /&gt;</code> Component we just created, and pass in the original event handler and any arguments, as <code>props</code>.</p>

<p>Note that the method, <code>handleClick()</code>, still needs to have its <code>this</code> context correctly bound. In this example, I chose to do the binding in the <code>constructor()</code>.  </p>

<pre><code>class Form extends React.Component {  
  constructor(props) {
    super(props);

    this.state = {
      name: "joe"
    };

    this.handleClick = this.handleClick.bind(this);  // Binding 'this'
  }

  handleClick(name) {
    console.log(name);
  };

  render() {
    return (
      &lt;Button
        handleClick={this.handleClick}  // Pass 'this.handleClick'
                                        // as a prop called, 'handleClick'

        name={this.state.name} // Pass the argument
                               // as a prop called, 'name'
      /&gt;
    );
  }
}
</code></pre>

<p>&nbsp;</p>

<p>The above example is pretty simple. Here's another example in <a href="https://codesandbox.io/s/oY825BRxK">React CodeSandbox</a> that further illustrates this pattern.</p>

<iframe src="https://codesandbox.io/embed/oY825BRxK?view=editor" style="width:100%; height:1150px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>

<hr>

<h5 id="appendixusingbabelstage2presets">Appendix: Using Babel Stage-2 Presets</h5>

<pre><code>// webpack.config.js

// Specify webpack to use the 'babel-loader' module, for .js file types.


var path = require('path');  
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {  
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index.bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader'
      },
      {
        exclude: /(node_modules)/,
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin({
    template: 'app/index.html'
  })]
}
</code></pre>

<pre><code>// .babelrc

// Include "stage-2", under "presets".


{
  "presets": ["env", "react", "stage-2"]
}
</code></pre>

<pre><code>// package.json

// Add "babel-preset-stage-2" as a Dev Dependency.


"devDependencies": {
  "babel-core": "^6.25.0",
  "babel-loader": "^7.1.1",
  "babel-preset-env": "^1.6.0",
  "babel-preset-react": "^6.24.1",
  "babel-preset-stage-2": "^6.24.1",
  "css-loader": "^0.28.4",
  "html-webpack-plugin": "^2.29.0",
  "prop-types": "^15.5.10",
  "style-loader": "^0.18.2",
  "webpack": "^3.3.0",
  "webpack-dev-server": "^2.5.1"
},
"dependencies": {
  "react": "^15.6.1",
  "react-dom": "^15.6.1"
}
</code></pre>]]></content:encoded></item><item><title><![CDATA[Webpack: Building React For Production on Windows]]></title><description><![CDATA[<p>I ran into some unexpected errors while trying to build React for production using a Windows machine <em>(which was undocumented in the React docs. No love for Windows machines? =p)</em>.</p>

<p>The below is just some documentation of my research for personal reference.</p>

<h5 id="macospackagejsonwebpackbuildscript">Mac OS: Package.json Webpack Build Script</h5>

<p>The</p>]]></description><link>http://duncanleung.com/webpack-building-react-for-production-on-windows/</link><guid isPermaLink="false">1c640338-3467-4ac4-8405-15c903c5db30</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Mon, 31 Jul 2017 14:54:26 GMT</pubDate><content:encoded><![CDATA[<p>I ran into some unexpected errors while trying to build React for production using a Windows machine <em>(which was undocumented in the React docs. No love for Windows machines? =p)</em>.</p>

<p>The below is just some documentation of my research for personal reference.</p>

<h5 id="macospackagejsonwebpackbuildscript">Mac OS: Package.json Webpack Build Script</h5>

<p>The <a href="https://facebook.github.io/react/docs/optimizing-performance.html#webpack">React docs</a> provide the following script:</p>

<pre><code>// package.json

  "scripts": {
    "build": "NODE_ENV='production' webpack -p"
  }
</code></pre>

<p>&nbsp;</p>

<h5 id="windowspackagejsonwebpackbuildscript">Windows: Package.json Webpack Build Script</h5>

<p>However, trying to run the above script on a Windows machine (even using cygwin) will give you the error:  </p>

<pre><code>'NODE_ENV' is not recognized as an internal or external command, operable program or batch file.  
</code></pre>

<p>&nbsp;</p>

<p>The script needs to be run slightly differently on Windows machines:</p>

<pre><code>// package.json

  "scripts": {
    "build": "set NODE_ENV=production &amp;&amp; webpack -p"
  }
</code></pre>

<hr>

<h3 id="understandingthescripts">Understanding The Scripts</h3>

<p>&nbsp;</p>

<h5 id="1packagejsonoptimizingwebpackforproduction">1. <code>package.json</code>: Optimizing webpack for Production</h5>

<p>The webpack production flag, <a href="https://webpack.github.io/docs/cli.html#production-shortcut-p"><code>webpack -p</code></a>, is shorthand for <code>--optimize-minimize --optimize-occurrence-order</code>.</p>

<p><code>--optimize-minimize</code>: Minimize scripts and CSS (if using css-loader).</p>

<p><code>--optimize-occurrence-order</code>: webpack assigns IDs to modules and chunks (I believe for caching validation purposes). <code>--optimize-occurrence-order</code> makes sure that commonly used ids will have a smaller id length.</p>

<pre><code>// package.json

// Set NODE_ENV for webpack to 'production'
// Use the Webpack 'production' shortcut, -p
  "scripts": {
    "build": "set NODE_ENV=production &amp;&amp; webpack -p"
  }
</code></pre>

<p>&nbsp;</p>

<h5 id="2webpackconfigjsbuildreactforproductionandminifyjs">2. <code>webpack.config.js</code>: Build React for Production and Minify JS</h5>

<p>In webpack, <a href="https://webpack.js.org/plugins/define-plugin/"><code>DefinePlugin</code></a> allows creating global constants that can be configured at compile time. This provides flexibility for different behaviors between development builds and release builds.</p>

<p>&nbsp;</p>

<h6 id="tellreacttousetheproductionversionofreacthttpsfacebookgithubioreactdocsoptimizingperformancehtml">Tell React to use the <a href="https://facebook.github.io/react/docs/optimizing-performance.html">production version of React</a></h6>

<p>This instance of <a href="https://webpack.js.org/guides/production/#node-environment-variable"><code>DefinePlugin</code></a> performs a search-and-replace on the original source code, and instances of <code>process.env.NODE_ENV</code> in the imported code is replaced by <code>"production"</code>.</p>

<p>React's internals has references to <code>process.env.NODE_ENV</code>. When set to, <code>"production"</code>, React removes warning messages to reduce file-size and increase performance.</p>

<pre><code>// webpack.config.js

    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    })
</code></pre>

<p>&nbsp;</p>

<h6 id="makewebpackminifyjavascriptcode">Make webpack Minify Javascript code</h6>

<p>webpack comes with UglifyJsPlugin, and uses UglifyJS to minimize the output.</p>

<pre><code>// webpack.config.js

    new webpack.optimize.UglifyJsPlugin()
</code></pre>

<hr>

<h5 id="completewebpackconfigjs">Complete webpack.config.js</h5>

<pre><code>// webpack.config.js

let path = require('path');  
let HtmlWebpackPlugin = require('html-webpack-plugin');  
let webpack = require('webpack');

let config = {  
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index.bundle.js',
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader'
      },
      {
        exclude: /(node_modules)/,
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  devServer: {
    historyApiFallback: true
  },
  plugins: [new HtmlWebpackPlugin({
    template: 'app/index.html'
  })]
};

if (process.env.NODE_ENV === 'production') {  
  config.plugins.push(
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    new webpack.optimize.UglifyJsPlugin()
  );
}

module.exports = config;  
</code></pre>]]></content:encoded></item><item><title><![CDATA[Avoiding React setState() Pitfalls]]></title><description><![CDATA[<p>I often read that <code>setState()</code> is one of the more misunderstood aspects of React.</p>

<p>Considering that managing component state is a fundamental aspect of React, I wanted to understand the common pitfalls and solutions around using <code>setState()</code>.</p>

<p>First, a quick overview of <code>setState()</code> and its behavior.</p>

<hr>

<h2 id="setstatesignature"><code>setState()</code> Signature:</h2>

<pre><code>setState(updater,</code></pre>]]></description><link>http://duncanleung.com/avoiding-react-setstate-pitfalls/</link><guid isPermaLink="false">2883addc-2d00-4ce4-a1be-ea824c15c921</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Sat, 15 Jul 2017 17:38:37 GMT</pubDate><content:encoded><![CDATA[<p>I often read that <code>setState()</code> is one of the more misunderstood aspects of React.</p>

<p>Considering that managing component state is a fundamental aspect of React, I wanted to understand the common pitfalls and solutions around using <code>setState()</code>.</p>

<p>First, a quick overview of <code>setState()</code> and its behavior.</p>

<hr>

<h2 id="setstatesignature"><code>setState()</code> Signature:</h2>

<pre><code>setState(updater, [callback])  
</code></pre>

<h6 id="setstatetakestwoarguments"><code>setState()</code> takes two arguments.</h6>

<ul>
<li>An <strong>updater</strong>
<ul><li>Either an <code>object literal</code> OR a <code>function</code>.</li></ul></li>
<li>An optional <strong>callback</strong>
<ul><li><code>setState()</code> is <em>asynchronous</em>.</li>
<li>The callback is called when the Component state <em>has actually updated</em>.</li></ul></li>
</ul>

<p>&nbsp;</p>

<h6 id="passingupdateranobjectliteral">Passing <code>updater</code> an <code>Object Literal</code></h6>

<ul>
<li>Use the object literal pattern for <em>simple state updates</em>.</li>
<li>Passing an object literal is succinct.</li>
</ul>

<pre><code>// Using an object literal in setState

this.setState({  
   selectedLang: 'Javascript'
});
</code></pre>

<h6 id="passingupdaterafunction">Passing <code>updater</code> a <code>Function</code></h6>

<ul>
<li>Use the updater function pattern when updates <em>need to reference the previous state</em>.</li>
<li>Passing an updater function provides access to <code>prevState</code> and current <code>props</code>.</li>
<li><code>prevState</code> is a reference to the previous state. It should not be directly mutated.</li>
</ul>

<p>The Updater Function Signature:  </p>

<pre><code>(prevState, props) =&gt; stateChange
</code></pre>

<p>The updater function should <em>build a new object</em> based on the input from <code>prevState</code> and <code>props</code>  </p>

<pre><code>// Using an updater function in setState to build a new object

this.setState((prevState, props) =&gt; {  
  return {counter: prevState.counter + props.increment};
});
</code></pre>

<p>&nbsp;</p>

<h2 id="setstatebehavior"><code>setState()</code> Behavior:</h2>

<p>When <code>setState()</code> is called it does two main things:</p>

<p><strong>1 - Queues changes to the component state (it is <em>asynchronous</em>)</strong></p>

<ul>
<li><strong>Note:</strong> If an <code>object literal</code> is passed as an updater, React first merges the object you passed to <code>setState()</code> into the current state.</li>
</ul>

<p><strong>2 - Tells React that the component (and children) needs to be re-rendered with the updated state.</strong></p>

<ul>
<li><p>React's reconciliation process</p>

<ul><li>Create a new React Element tree (an object representation of the UI).</li>
<li>Diffs the new tree against the old tree.</li>
<li>Determines what changed, based on the updater passed to <code>setState()</code>.</li>
<li>Updates the DOM.</li></ul></li>
<li><p><strong>Note:</strong> Use React's <a href="https://facebook.github.io/react/docs/react-component.html#updating">lifecycle methods</a> to run code at different stages in reconciliation</p>

<ul><li><strong><a href="https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate"><code>shouldComponentUpdate</code></a></strong>: Allows determining if the component should update itself by inspecting the previous and new state.
<ul><li>If <code>return false</code>, then <code>componentWillUpdate</code> and <code>componentDidUpdate</code> are <strong>not executed</strong>. The component UI won't re-render.</li>
<li><strong><code>this.state</code> will still be updated</strong> within the component.</li></ul></li>
<li><strong><a href="https://facebook.github.io/react/docs/react-component.html#componentwillupdate"><code>componentWillUpdate</code></a></strong>: Run any code <em>before</em> the new state is set and rendering happens</li>
<li><a href="https://facebook.github.io/react/docs/react-component.html#render"><code>render</code></a>: Render the updates visually to the DOM</li>
<li><strong><a href="https://facebook.github.io/react/docs/react-component.html#componentdidupdate"><code>componentDidUpdate</code></a></strong>: Run any code <em>after</em> the new state is set and the component has re-rendered</li></ul></li>
</ul>

<hr>

<h2 id="commonpitfallswithsetstate">Common Pitfalls with <code>setState()</code></h2>

<h4 id="pitfall1tryingtomodifystatedirectly">Pitfall 1: Trying to modify <code>state</code> directly</h4>

<p>The first mistake with <code>setState()</code> is not using <code>setState()</code>! =)</p>

<ul>
<li>Do not modify <code>state</code> directly.</li>
<li>Modifying <code>this.state</code> directly will not trigger a Component re-render.</li>
<li>The only place where <code>this.state</code> should be assigned is in the component's <code>constructor</code>.</li>
</ul>

<pre><code>// WRONG: This will not re-render the component

this.state.discount = false;  
</code></pre>

<h6 id="solutionusesetstate">Solution: <code>Use setState()</code></h6>

<p><code>setState()</code> will trigger a re-render of the Component.</p>

<pre><code>// CORRECT: Use setState()

this.setState({  
  discount: false
})
</code></pre>

<p><strong>Aside:</strong> When should something be stored in Component <code>state</code>?</p>

<ul>
<li>If you don't use something in <code>render()</code>, it shouldn't be in <code>this.state</code>.</li>
</ul>

<p>&nbsp;</p>

<h4 id="pitfall2tryingtousesetstatesynchronously">Pitfall 2: Trying to use <code>setState</code> synchronously</h4>

<p><code>setState()</code> is <strong>asynchronous</strong>. Do not call <code>setState</code> on one line and assume the state has already changed on the next line.</p>

<ul>
<li><code>setState()</code> is a <em>request to update state</em>, rather than an immediate command to update state.</li>
<li><code>setState()</code> does not always immediately update the component.</li>
</ul>

<pre><code>// WRONG: setState() should not be used synchronously

// assuming this.state = { orders: 0 }
this.setState({  
  orders: 1
});

console.log(this.state.orders); // BUG! Prints out: 0  
</code></pre>

<p>There are two solutions to this mistake:</p>

<ul>
<li>Use the <code>componentDidUpdate()</code> lifecycle method (<em>recommended by the React team</em>).</li>
<li>Pass a <code>callback</code> as a second argument to <code>setState()</code>.</li>
</ul>

<p>Using <code>componentDidUpdate</code> or a setState callback (<code>setState(updater, callback)</code>) guarantees your code will execute after the state update has been applied.</p>

<h6 id="solution1usethecomponentdidupdatelifecyclemethod">Solution 1: Use the <code>componentDidUpdate()</code> lifecycle method</h6>

<p><code>componentDidUpdate()</code> is invoked immediately after updating occurs (but is not called on the initial render of the Component).</p>

<pre><code>// CORRECT: Use the componentDidUpdate() lifecycle method

componentDidUpdate(prevProps, prevState) {  
  console.log(this.state.orders); // Prints out: 1
}
</code></pre>

<h6 id="solution2passacallbackfunctiontosetstate">Solution 2: Pass a callback function to <code>setState()</code></h6>

<p>The second parameter to <code>setState()</code> is an optional callback function that will be executed once setState is completed and the component is re-rendered.</p>

<pre><code>// CORRECT: Pass a callback as a second argument to setState()

// assuming this.state = { orders: 0 }
this.setState({  
  orders: 1
}, () =&gt; {
  console.log(this.state.orders); // Prints out: 1
});
</code></pre>

<p>&nbsp;</p>

<h4 id="pitfall3tryingtouseapreviousvalueofstate">Pitfall 3: Trying to use a previous value of state</h4>

<p><code>setState()</code> is <strong>asynchronous</strong>. Consequently, the vales of <code>this.state</code> should not be used for calculating the next state.</p>

<ul>
<li><code>this.props</code> and <code>this.state</code> may be updated asynchronously.</li>
<li><code>this.state</code> should not be used to calculate the next state.</li>
</ul>

<pre><code>// WRONG: Don't rely on this.state to calculate the next state

this.setState({  
  orders: this.state.orders + this.props.increment,
});
</code></pre>

<h6 id="solutionusetheupdaterfunctionformtoaccessprevstate">Solution: Use the updater <code>function</code> form to access <code>prevState</code></h6>

<p>The first argument of the updater function, <code>prevState</code>, provides access to the previous state:</p>

<p>Updater function signature:  </p>

<pre><code>(prevState, props) =&gt; stateChange
</code></pre>

<pre><code>// CORRECT: Use the updater function form to access prevState

this.setState((prevState, props) =&gt; ({  
  orders: prevState.orders + props.increment
}));
</code></pre>

<p>&nbsp;</p>

<h4 id="pitfall4tryingtoissuemultiplesetstatecalls">Pitfall 4: Trying to issue multiple <code>setState()</code> calls</h4>

<p>Multiple <code>setState()</code> calls during the same cycle may be <strong>batched</strong>. This is specifically an issue when passing <code>updater</code> an <code>object literal</code>.</p>

<ul>
<li><code>setState()</code> performs a shallow merge of the updater object into the new state.</li>
<li>Subsequent <code>setState()</code> calls will override values from previous calls in the same cycle.</li>
<li>If the updater objects have the same keys, the value of the key, of the last object passed to <code>Object.assign()</code>, overrides the previous value.</li>
</ul>

<pre><code>// WRONG: Using an object literal with multiple setState calls during the same cycle will shallow merge the objects

// assuming this.state = { orders: 0 };
this.setState({ orders: this.state.orders + 1});  
this.setState({ orders: this.state.orders + 1});  
this.setState({ orders: this.state.orders + 1});

// --&gt; OUTPUT: this.state.orders will be 1, not 3 as we would expect


// It is equivalent of an Object.assign, which performs a shallow merge
// The orders will only be incremented once

Object.assign(  
  previousState,
  {orders: state.orders + 1},
  {orders: state.orders + 1},
  {orders: state.orders + 1},
  ...
)
</code></pre>

<h6 id="solutionusetheupdaterfunctionformtoqueuestateupdates">Solution: Use the updater <code>function</code> form to queue state updates</h6>

<p>By passing updater a function, the updates will be queued and later executed in the order they were called.</p>

<pre><code>//CORRECT: Use the updater function form to queue state updates

// assuming this.state = { orders : 0 };
this.setState((prevState) =&gt; ({ orders: prevState.orders + 1}));  
this.setState((prevState) =&gt; ({ orders: prevState.orders + 1}));  
this.setState((prevState) =&gt; ({ orders: prevState.orders + 1}));

// --&gt; OUTPUT: this.state.orders will be 3
</code></pre>]]></content:encoded></item><item><title><![CDATA[Thinking in React - Fetching Data with AJAX]]></title><description><![CDATA[<p>Just jotting down some <em>'aha'</em> moments in my understanding of React:</p>

<ul>
<li>React provides a declarative library that keeps the DOM in sync with your data.</li>
<li>React components just render <code>props</code> and <code>state</code>.</li>
<li>React components just represent the UI at a certain point in time.</li>
<li>Use the <code>componentDidMount</code> method to fetch</li></ul>]]></description><link>http://duncanleung.com/thinking-in-react-fetching-data-ajax/</link><guid isPermaLink="false">f9963d4e-2be4-4d87-88ab-f46d2e7c1219</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Thu, 22 Jun 2017 15:10:00 GMT</pubDate><content:encoded><![CDATA[<p>Just jotting down some <em>'aha'</em> moments in my understanding of React:</p>

<ul>
<li>React provides a declarative library that keeps the DOM in sync with your data.</li>
<li>React components just render <code>props</code> and <code>state</code>.</li>
<li>React components just represent the UI at a certain point in time.</li>
<li>Use the <code>componentDidMount</code> method to fetch data with AJAX.</li>
</ul>

<p><strong><em>TLDR; Skip to the codesandbox snippet below to take a look at the code</em></strong></p>

<hr>

<p><strong><em>Random Aside:</em></strong>
<em>The cool thing is that grokking this 'React Thinking' has helped to structure my code at work. Our stack at iHerb is just jQuery *cries</em><em>*, and so it's super easy to start writing a spaghetti mess. Our team made some significant strides by refactoring to follow the module and prototype pattern, but having this 'React Thinking', making the UI a representation of application state, has drastically increased the maintainability of our code.</em></p>

<hr>

<h6 id="reactcomponentsjustrenderpropsandstate">React Components Just Render <code>props</code> and <code>state</code></h6>

<p>React just renders components, and data in React comes from two places: <code>props</code> or <code>state</code>.</p>

<p>When thinking about where to fetch data in React, the underlying concept is that data needs to somehow get into the component's <code>props</code> or <code>state</code>.</p>

<h6 id="reactcomponentsrepresenttheuiatacertainpointintime">React Components Represent the UI at a Certain Point in Time</h6>

<p>The beauty of React is that a component is just supposed to represent the UI at a certain point in time.</p>

<p>The <code>render()</code> method, therefore, should not have any code that contain side effects, nor anything that is asynchronous in nature. It is just suppose take the current <code>props</code> and <code>state</code> and represent that as DOM elements.</p>

<h6 id="fetchdatainthecomponentdidmountlifecyclemethod">Fetch Data in the <code>componentDidMount</code> lifecycle method</h6>

<p>The <code>componentDidMount</code> method is the recommended place to make any AJAX data calls.</p>

<p>The <code>componentDidMount</code> method only executes once during a component’s life: at the point when the component mounts to the DOM for the first time.</p>

<p>By using this lifecycle method, it is clear that data won’t be loaded until after the initial render and enforces the pattern of setting up an initial default state to prevent any undefined state that could result in unexpected app behaviour.</p>

<hr>

<p>Below is a simple example of how we can update a component’s state (a list of GitHub repos) with <code>this.setState</code> in the <code>componentDidMount</code> method. Once the state is updated, React triggers a re-render, and then the repos are rendered to the DOM.</p>

<pre><code>export default class GitHubRepos extends React.Component {  
  constructor(props) {
    super(props);

    this.state = {
      repos: []
    };
  }
  componentDidMount() {
    axios
      .get(
        window.encodeURI(
          `https://api.github.com/search/repositories
             q=stars:&gt;1+language:javascript&amp;sort=stars&amp;order=desc&amp;type=Repositories`,
        ),
      )
      .then(response =&gt; {
        const repos = response.data.items;
        this.setState({
          repos
        });
      })
      .catch(error =&gt; {
        console.log(error);
      });
  }
</code></pre>

<p>The full code is in my codesandbox below:</p>

<iframe src="https://codesandbox.io/embed/0RjoGzVoK?module=wRo98" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>  

<hr>

<h6 id="caveatwithfetchingdataincomponentwillmount">Caveat with Fetching Data in <code>componentWillMount</code></h6>

<p>It seems logical to use the <code>componentWillMount</code> method to load data, since the goal is to have data loaded into the app <em>before</em> it gets rendered to the DOM.</p>

<p>However, fetching data with AJAX happens asynchronously. There is no way to pause or delay React from continuing to render the component <em>(maybe with a hacky setTimeout? I haven't tried..)</em>.</p>

<p>The component will end up rendering before that data is loaded.</p>

<p>The problem with using <code>componentWillMount</code> is <strong>it isn't explicit</strong> (to the developer / maintainer) that the component will render without data at least once. By assuming that the component will have data returned on first-render, the developer could naively skip setting up the component's default <code>state</code>, and the handling of default <code>state</code>.</p>

<p>Without setting default a <code>state</code>, the initial render of the component will have a <code>state</code> of <code>undefined</code> <em>(and probably some bugs to track down!)</em>.</p>]]></content:encoded></item><item><title><![CDATA[Cookies vs localStorage vs sessionStorage]]></title><description><![CDATA[<p>I thought this video by Beau at Free Code Camp was awesome.</p>

<p>I pulled this table out from the video for comparing between <code>cookies</code>, <code>localStorage</code>, and <code>sessionStorage</code>.</p>

<h4 id="comparingcookieslocalstorageandsessionstorage">Comparing Cookies, localStorage, and sessionStorage</h4>

<table border="1" style="height: 171px;" width="670">  
<tbody>  
<tr>  
<td style="width: 160px;"></td>  
<td style="width: 160px;"><strong>Cookies</strong></td>  
<td style="width: 161px;"><strong>Local Storage</strong></td>  
<td style="width: 161px;"><strong>Session Storage</strong></td>  
</tr>  
<tr>  
<td style="width: 160px;"><strong>Capacity</strong></td>  
<td style="width: 160px;">4kb</td>  
<td style="width: 161px;">10mb</td>  
<td style="width: 161px;">5mb</td>  
</tr>  
<tr>  
<td style="width: 160px;"><strong>Browsers</strong></td>  
<td style="width: 160px;">HTML4/Html5</td>  
<td style="width: 161px;">Html5</td>  
<td style="width: 161px;">Html5</td>  
</tr>  
<tr>  
<td style="width: 160px;"><strong>Accessible from</strong></td>  
<td style="width: 160px;">Any window</td></tr></tbody></table>]]></description><link>http://duncanleung.com/cookies-vs-localstorage-vs-sessionstorage/</link><guid isPermaLink="false">0b77082d-92a3-4205-8bd3-3cf4f52477d7</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Tue, 20 Jun 2017 15:43:03 GMT</pubDate><content:encoded><![CDATA[<p>I thought this video by Beau at Free Code Camp was awesome.</p>

<p>I pulled this table out from the video for comparing between <code>cookies</code>, <code>localStorage</code>, and <code>sessionStorage</code>.</p>

<h4 id="comparingcookieslocalstorageandsessionstorage">Comparing Cookies, localStorage, and sessionStorage</h4>

<table border="1" style="height: 171px;" width="670">  
<tbody>  
<tr>  
<td style="width: 160px;"></td>  
<td style="width: 160px;"><strong>Cookies</strong></td>  
<td style="width: 161px;"><strong>Local Storage</strong></td>  
<td style="width: 161px;"><strong>Session Storage</strong></td>  
</tr>  
<tr>  
<td style="width: 160px;"><strong>Capacity</strong></td>  
<td style="width: 160px;">4kb</td>  
<td style="width: 161px;">10mb</td>  
<td style="width: 161px;">5mb</td>  
</tr>  
<tr>  
<td style="width: 160px;"><strong>Browsers</strong></td>  
<td style="width: 160px;">HTML4/Html5</td>  
<td style="width: 161px;">Html5</td>  
<td style="width: 161px;">Html5</td>  
</tr>  
<tr>  
<td style="width: 160px;"><strong>Accessible from</strong></td>  
<td style="width: 160px;">Any window</td>  
<td style="width: 161px;">Any window</td>  
<td style="width: 161px;">Same tab</td>  
</tr>  
<tr>  
<td style="width: 160px;"><strong>Expires</strong></td>  
<td style="width: 160px;">Manually set</td>  
<td style="width: 161px;">Never</td>  
<td style="width: 161px;">On tab close</td>  
</tr>  
<tr>  
<td style="width: 160px;"><strong>Storage Location</strong></td>  
<td style="width: 160px;">Browser and server</td>  
<td style="width: 161px;">Browser only</td>  
<td style="width: 161px;">Browser only</td>  
</tr>  
<tr>  
<td style="width: 160px;"><strong>Sent with requests</strong></td>  
<td style="width: 160px;">Yes</td>  
<td style="width: 161px;">No</td>  
<td style="width: 161px;">No</td>  
</tr>  
</tbody>  
</table>

<iframe width="1280" height="720" src="https://www.youtube.com/embed/AwicscsvGLg?rel=0" frameborder="0" allowfullscreen></iframe>

<h5 id="securityconsiderations">Security Considerations</h5>

<p><em>(Source: <a href="https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies">https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies</a>)</em></p>

<ul>
<li><code>Cookies</code>, <code>sessionStorage</code> and <code>localStorage</code> should only be used for persisting non-sensitive data between pages since they can be read and modified from the client</li>
<li><code>Cookies</code> information can be intercepted in transit if not on HTTPS</li>
<li><code>Cookies</code> should use the <code>HTTPonly</code> flag will prevent access to the cookies and values from JavaScript</li>
<li><code>Cookies</code> should not be used to store large amounts of information since all <code>cookies</code> valid for a page are sent for every request to the same domain.</li>
</ul>]]></content:encoded></item><item><title><![CDATA[The Critical Rendering Path - Optimizing Script Loading]]></title><description><![CDATA[<p>I recently did a weekend side project to ramp up my Chrome Dev Tools chops by using the <a href="https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/timeline-tool">Timeline tool</a> to analyze and optimize a website's page load performance, as it relates to JavaScript loading and execution.</p>

<p>I quickly realized, though, that improving my Dev Tools proficiency meant first solidifying</p>]]></description><link>http://duncanleung.com/the-critical-rendering-path-optimizing-script-loading/</link><guid isPermaLink="false">e5da4806-9069-491e-a747-b00055be6492</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Tue, 14 Mar 2017 07:54:57 GMT</pubDate><content:encoded><![CDATA[<p>I recently did a weekend side project to ramp up my Chrome Dev Tools chops by using the <a href="https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/timeline-tool">Timeline tool</a> to analyze and optimize a website's page load performance, as it relates to JavaScript loading and execution.</p>

<p>I quickly realized, though, that improving my Dev Tools proficiency meant first solidifying my understanding on the browser; specifically, the <a href="https://developers.google.com/web/fundamentals/performance/critical-rendering-path/">Critical Rendering Path</a>.</p>

<p><em>You have to know what you're looking for, in order to analyze it, right? =)</em></p>

<p><strong>TLDR;</strong>
<em>Optimizing the Critical Rendering Path involves optimizing the dependencies between HTML, CSS, and JavaScript and reducing the time required to process and turn them into rendered pixels.</em></p>

<hr>

<h5 id="criticalrenderingpath">Critical Rendering Path</h5>

<p>Let's take a high level look at the Critical Rendering Path. (If you want to dig deep into the full path, check out <a href="https://developers.google.com/web/fundamentals/performance/critical-rendering-path/">Google's Web Fundamentals</a>.)</p>

<p>The Critical Rendering Path can be separated into two main portions: network transmission, and browser processing.</p>

<p><strong>Network Transmission:</strong>
Involves the key steps to receive the HTML, CSS, and JavaScript assets.</p>

<p><strong>Render Processing:</strong>
Involves the processing steps to turn these assets into rendered pixels (first paint).</p>

<p>In order to render a page, the web browser needs to receive the HTML and CSS, and respectively build the Document Object Model (DOM) and the CSS Object Model (CSSOM). Thus, both HTML and CSS are render blocking resources.</p>

<p>In addition to render blocking HTML and CSS, by default (without the <code>async</code> attribute), JavaScript execution is also a render blocking resource as the execution of any included scripts will block the browser parser until the script's execution is completed.</p>

<h5 id="breakingdownthecriticalrenderingpath">Breaking Down the Critical Rendering Path</h5>

<p>When you request a webpage (aka. type in a URL), the website's server sends back the page's HTML. HTML documents not only contain the content of the site, but also references to any external CSS and JavaScript resources.</p>

<h6 id="buildingthedomandccsom">Building the DOM and CCSOM</h6>

<p>After the HTML is received, the browser begins parsing the received bytes to create the Document Object Model DOM.</p>

<p><strong>Bytes → Characters → Tokens → Nodes → Document Object Model</strong></p>

<p>While parsing the HTML, if the browser comes across an external resource reference, the browser will send off a network request to fetch the file. For example, when the browser comes across a link tag <code>&lt;link href="style.css" rel="stylesheet"&gt;</code>, it will send off a network request to retrieve the CSS stylesheet .</p>

<p>When the CSS file is received, the same parsing process happens on the CSS file to create the CSS Object Model.</p>

<p><strong>Bytes → Characters → Tokens → Nodes → CSS Object Model</strong></p>

<h6 id="javascriptblocksdomcreationandpagerendering">JavaScript Blocks DOM Creation and Page Rendering</h6>

<p>JavaScript resources also have the potential to block and delay the render of the page as the execution of any scripts will block the browser parser.</p>

<p><img src="http://res.cloudinary.com/leungd/image/upload/v1489474725/analysis-dom-css-js_aqn0p8.png" alt="DOM, CSSOM, Parser Blocking Javascript" title="">  <em><a href="https://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp">Image: Parser blocking script files</a></em></p>

<p>When the browser comes across an inline <code>&lt;script&gt;</code> tag, the browser will  pause/block the parser and DOM creation process for the entire time it takes to both fetch the script across the network, and for the JavaScript engine to execute the script.</p>

<p><strong><em>This parser blocking behaviour is detrimental to user-experience, since a network roundtrip could add thousands of milliseconds of delay to the critical rendering path!</em></strong></p>

<p>Furthermore, another important behaviour to be aware of is that script execution will only begin after all prior referenced CSS resources have been downloaded and their CCSOM has been constructed.</p>

<p>Basically, <strong><em>script execution is itself blocked</em></strong> until the CCSOM has been constructed.</p>

<p>As you can see, there are many ways that Javascript resources can block the Critical Rendering Path and time to first render.</p>

<h5 id="optimizingthecriticalrenderingpath">Optimizing the Critical Rendering Path</h5>

<p>Essentially, optimizing the Critical Rendering Path involves minimizing the total amount of time spent performing each step in the render path:</p>

<ol>
<li>Processing HTML markup and building the DOM tree  </li>
<li>Processing CSS markup and building the CSSOM tree  </li>
<li>Combining the DOM and CSSOM into a render tree  </li>
<li>Executing JavaScript files</li>
</ol>

<p><em>Optimizing the <a href="https://developers.google.com/web/fundamentals/performance/rendering/reduce-the-scope-and-complexity-of-style-calculations">CSSOM and the complexity of style calculations</a> has it's own focus. I'll just be looking at optimizing script loading in this article.</em></p>

<hr>

<h5 id="optimizingscriptloading">Optimizing Script Loading</h5>

<p>Okay, that was a lot of background info - let's dig into my take-aways on optimizing script loading.</p>

<h6 id="baselineregularscriptloading">Baseline - Regular Script Loading:</h6>

<pre><code>&lt;script src="first.js"&gt;&lt;/script&gt;  
&lt;script src="//domain.com/second.js"&gt;&lt;/script&gt;  
</code></pre>

<p>In this situation, the browser will block the parser while it downloads both scripts in parallel. The scripts will then be executed in order of declaration in the HTML.</p>

<ul>
<li><code>second.js</code> won’t execute until <code>first.js</code> has executed.</li>
<li><code>first.js</code> won’t execute until the CSSOM has been fully parsed, and until any previous scripts are executed.</li>
<li>The Critical Rending Path is blocked while all this is happening.</li>
</ul>

<p><strong>Comments:</strong>
This is the least optimal method of loading scripts.</p>

<p>Even if we try to prevent blocking the DOM by placing the <code>&lt;script&gt;</code> at the end of the document, right before the <code>&lt;/body&gt;</code> tag, the browser won't fetch the script until the whole document has been parsed.</p>

<p>Ideally, we would like to begin fetching these scripts asynchronously, as soon as possible, and then execute them when they're received across the network.</p>

<h6 id="asynchronouslyloadscriptswithasync">Asynchronously Load Scripts with <code>async</code></h6>

<p><img src="http://res.cloudinary.com/leungd/image/upload/v1488873095/analysis-dom-css-js-async_ppfwnh.png" alt="DOM, CSSOM, async JavaScript Critical Render Path" title=""> <em><a href="https://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp">Image: async script files</a></em></p>

<pre><code>&lt;script src="first.js" async&gt;&lt;/script&gt;  
&lt;script src="//domain.com/second.js" async&gt;&lt;/script&gt;  
</code></pre>

<p>In this situation, the the <code>async</code> attribute tells the browser that the script is not part of the critical rendering path. The browser downloads both scripts in parallel, but the parser continues to construct the DOM while the resources are being fetched.</p>

<p>As soon as a script file is received across the network, it will be executed <strong>in the order it is received</strong>. This can introduce dependency issues as the order of declaration is not maintained!</p>

<ul>
<li>The browser parser is not blocked while scripts are fetched.</li>
<li>Scripts will execute as soon as it is retrieved, regardless of the order it was defined in the document.</li>
<li>Scripts do not wait for the CSSOM to be fully parsed.</li>
</ul>

<p><strong>Comments:</strong>
Using the <code>async</code> attribute is the best practice as it allows script references to be placed in the <code>&lt;head&gt;</code>, so that they can be fetched early on and asynchronously.</p>

<p>However, even <code>async</code> scripts still block the browser parser during script execution. So a long-running script could still potentially delay the first paint.</p>

<h6 id="deferscriptloadingwithdefer">Defer Script Loading with <code>defer</code></h6>

<p>In this situation, the the <code>defer</code> attribute not only tells the browser to prevent the parser from being blocked while the scripts are being fetched, but to also delay script execution until after the document has been parsed (just before <code>domContentLoaded</code> is fired).</p>

<p>All deferred scripts will also maintain their declaration order.</p>

<pre><code>&lt;script src="first.js" defer&gt;&lt;/script&gt;  
&lt;script src="//domain.com/second.js" defer&gt;&lt;/script&gt;  
</code></pre>

<p><strong>Comments:</strong>
The best uses for <code>defer</code> are for any non-critical scripts, like analytics, ad networks, social networks, etc. that don't provide any core functionality to your website / app.</p>]]></content:encoded></item><item><title><![CDATA[Javascript's 'this' Assignment]]></title><description><![CDATA[<p>Every week our Front End Developer team gathers to discuss/share any site-wide initiatives that are in the pipeline.</p>

<p>In addition to administrative announcements, we each take turns to give a mini presentation, which we've unoriginally called Front End Developer Talks, aka FED Talks <em>(hopefully TED Talks doesn't chase us</em></p>]]></description><link>http://duncanleung.com/javascripts-this-assignment/</link><guid isPermaLink="false">1f28d655-652a-4697-9589-9092f3ec4d4d</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Mon, 13 Feb 2017 09:02:48 GMT</pubDate><content:encoded><![CDATA[<p>Every week our Front End Developer team gathers to discuss/share any site-wide initiatives that are in the pipeline.</p>

<p>In addition to administrative announcements, we each take turns to give a mini presentation, which we've unoriginally called Front End Developer Talks, aka FED Talks <em>(hopefully TED Talks doesn't chase us on trademark infringement...)</em>.</p>

<p>It's both a way to share knowledge, and a medium for us to <a href="https://www.youtube.com/watch?v=l9JXH7JPjR4">practice talking to developers</a>.</p>

<p>Generally the topic is anything fun/cool/random that we've been working on, or a new technology that we've been experimenting with.</p>

<p>This past week was my turn and I shared two things: <br>
1. My <a href="http://duncanleung.com/jquery-use-the-source-code/">journey into jQuery's source code</a> <br>
2. A fun little exercise on Javscript's <code>this</code> assignment I had been playing around in a <a href="http://codepen.io/duncanleung/pen/ZBLqda">Codepen</a>.</p>

<p>I'll take you through an exercise on Javascript's <code>this</code> assignment.</p>

<h5 id="example1thispointstowindowinagloballyinvokedfunction">Example 1: <code>this</code> points to <code>window</code>, in a globally invoked function</h5>

<pre><code>//Global variable, greeting.
var greeting = 'hello';

//Global function, sayGreeting.
function sayGreeting(){  
    console.log('greeting:', this.greeting);
}

sayGreeting(); //Result: hello  
</code></pre>

<p>In this example the variable, <code>greeting</code>, and the function, <code>sayGreeting</code>, are both in the global context.</p>

<p><code>sayGreeting()</code> is called in the global context, so the keyword <code>this</code> in <code>sayGreeting</code> points to <code>window</code> when it is invoked.</p>

<h5 id="example2thispointstotheobjectinaninvokedmethod">Example 2: <code>this</code> points to the object, in an invoked method</h5>

<pre><code>//Constructor French which stores a property, greeting
var French = function (greeting){  
    this.greeting = greeting;
}

//French.prototype which has a method sayGreeting
French.prototype = {  
  sayGreeting: function() {
    console.log('greeting:', this.greeting);
  }
}

//Create a new object, louis
var louis = new French('bonjour');

louis.sayGreeting() //Result: bonjour  
</code></pre>

<p>In this example the variable, <code>louis.greeting</code>, and the method, <code>louis.sayGreeting</code>, are both properties of the object louis.</p>

<p><code>louis.sayGreeting()</code> is called in the context of the object <code>louis</code>, the keyword <code>this</code> in <code>louis.sayGreeting</code> points to the object louis, when it is invoked.</p>

<h5 id="questionwhatdoesthispointtowhenamethodisassignedtoaglobalvariableandinvoked">Question: What does <code>this</code> point to, when a method is assigned to a global variable and invoked?</h5>

<pre><code>//borrowedGreeting points to the method, louis.sayGreeting
var borrowedGreeting = louis.sayGreeting;

borrowedGreeting(); //Result: ??  
</code></pre>

<p>So now we have an interesting case!</p>

<p><code>borrowedGreeting</code> is a global variable, which points to the method, <code>louis.sayGreeting</code>, on the object <code>louis</code>.</p>

<p>Essentially, <code>borrowedGreeting</code> will <code>console.log(this.greeting)</code>. However, which <code>this</code> does it point to?</p>

<p>There is a global variable, <code>greeting</code>. <br>
But there is also a property, <code>louis.greeting</code>.</p>

<pre><code>borrowedGreeting(); //Result: hello  
</code></pre>

<h5 id="takeawaythispointstotheobjectwhichinvokedthefunction">Take Away: <code>this</code> points to the <em>object which invoked</em> the function</h5>

<p>Interesting! Even though <code>borrowedGreeting</code> points to the method <code>louis.sayGreeting</code>, the object which invoked the function is <code>window</code>.</p>

<p>We can look at it another way:  </p>

<pre><code>window.borrowedGreeting()  
</code></pre>

<p>A quick shortcut to figuring out the <code>this</code> assignment in a function, is to look to the left of the function call to see which object is invoking it.</p>

<h5 id="furtherreadingassignthethiscontextoffunctioncalls">Further Reading: Assign the <code>this</code> context of function calls</h5>

<p>If we wanted to get <code>borrowedGreeting</code> to log out <code>bonjour</code>, we can use <code>Function.prototype.call()</code> to assign the <code>this</code> context of the function.</p>

<pre><code>borrowedGreeting.call(louis); //Result: bonjour  
</code></pre>

<p>For a full explanation, I'll point you to this great article by one of my Javascript heros, Yehuda Katz: <a href="http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/">Understanding Javascript Function Invocation and "this"</a></p>

<p>Hope you had fun following through this little exercise!</p>]]></content:encoded></item><item><title><![CDATA[jQuery - Use the Source Code!]]></title><description><![CDATA[<p>After debugging a production issue with our product carousels by diving into the <a href="http://getbootstrap.com/javascript/#carousel">Bootstrap carousel</a> source code, I thought it'd be a fun activity to start looking into the source of some other libraries that we use.</p>

<p>The obvious starting point was jQuery, since it's at the core of all</p>]]></description><link>http://duncanleung.com/jquery-use-the-source-code/</link><guid isPermaLink="false">9f3ec3e9-c605-4cf0-84f7-4fe13a605071</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Mon, 13 Feb 2017 05:32:52 GMT</pubDate><content:encoded><![CDATA[<p>After debugging a production issue with our product carousels by diving into the <a href="http://getbootstrap.com/javascript/#carousel">Bootstrap carousel</a> source code, I thought it'd be a fun activity to start looking into the source of some other libraries that we use.</p>

<p>The obvious starting point was jQuery, since it's at the core of all our DOM manipulation code we write.</p>

<p>Here's a quick link: <a href="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js">https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js</a></p>

<p><em>*I didn't get too far into the source since it's a pretty long library, but I did have two interesting take-aways.</em></p>

<h4 id="1whatisjqueryfn">1. What is jQuery.fn?</h4>

<p>One of the first questions I had in mind was regarding <code>jQuery.fn</code>. I previously knew that <a href="https://learn.jquery.com/plugins/basic-plugin-creation/">writing a jQuery plugin</a> involves defining a new method on the <code>jQuery.fn</code> object, but why, and what is, <code>jQuery.fn</code>?</p>

<p>Near the top of jQuery's source lies the answer (well, part of the answer).  </p>

<pre><code>jQuery.fn = jQuery.prototype { ... }  
</code></pre>

<p>That makes sense. If we want to create a new plugin that we can use from the jQuery object, we need to add it to jQuery's prototype object.</p>

<p>That's a standard Javascript pattern called the <a href="https://addyosmani.com/resources/essentialjsdesignpatterns/book/#prototypepatternjavascript">Prototype Pattern</a>.</p>

<p>Still, that seems like a strange pattern of creating a pointer to the <code>jQuery.prototype</code> called <code>jQuery.fn</code>. After a bit of Googling, I came across this Google Groups discussion, <a href="https://groups.google.com/d/msg/jquery-en/K9aNKgW4PtM/zuOPh7ONmbwJ">jQuery Prototype Magic</a>.</p>

<blockquote>
  <p><code>$.prototype</code> wasn't used for anything; instead, every time a jQuery object was created, all of the method references found in <code>$.fn</code> were copied, one by one, into the new jQuery object.</p>
  
  <p>As you can guess, this was a bit slow, and I came up with a patch to use <code>$.prototype</code> in the conventional manner instead of copying all the methods. <code>$.fn</code> was kept as an alias of <code>$.prototype</code> for compatibility with existing plugins that already used <code>$.fn</code>.</p>
</blockquote>

<p>**So the main take away is, <code>jQuery.fn</code> points to <code>jQuery.prototype</code>, and jQuery.fn is still used for backwards compatibility sake.</p>

<h4 id="2ddoesnttechnicallyreturnajqueryobject">2. <code>$(...)</code> doesn't <em>'technically'</em> return a jQuery object</h4>

<pre><code>// Define a local copy of jQuery
var jQuery = function( selector, context ) {

        // The jQuery object is actually just the
        // init constructor 'enhanced'
        return new jQuery.fn.init( selector, context );
};

var init = jQuery.fn.init = function(...) {...};

init.prototype = jQuery.fn;  
</code></pre>

<p>We're all taught that when we use the <code>$(...)</code> selector, jQuery returns a new jQuery object with a collection of elements for you to act on.</p>

<p>Interestingly though, jQuery's source reveals that the constructor is actually <code>jQuery.fn.init</code>. So <em>'technically'</em>, we're actually getting back a new <code>jQuery.fn.init</code> object.</p>

<p>That leads to another interesting line of code:  </p>

<pre><code>init.prototype = jQuery.fn;  
</code></pre>

<p>The reason for this line of code explained by the 4 things that happen when we use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a> in Javascript</p>

<ol>
<li>A new object is created, inheriting from the constructor's prototype  </li>
<li>The constructor function is called with any specified arguments  </li>
<li><code>this</code> is bound to the newly created object  </li>
<li>The newly created object is returned</li>
</ol>

<p>So, <code>new jQuery.fn.init( selector, context )</code> returns a new <code>jQuery.fn.init</code> object. However, the prototype of <code>jQuery.fn.init</code> is empty.</p>

<p>Since we want our new jQuery object to have access to all the useful jQuery methods that we know and love like <code>.find()</code> and <code>.addClass()</code>, the prototype of <code>init</code> needs to point to jQuery's prototype in access jQuery's other methods.</p>

<p>You can think of  </p>

<pre><code>init.prototype = jQuery.fn;  
</code></pre>

<p>to be re-written as  </p>

<pre><code>jQuery.prototype.init.prototype = jQuery.prototype  
</code></pre>

<p>Whew, that was a mouthful, but hopefully that sheds some light on what jQuery is actually doing when you're using it!</p>]]></content:encoded></item><item><title><![CDATA[Emmet for JSX on .js Files - Visual Studio Code]]></title><description><![CDATA[<p><strong>To have Emmet recognize jsx in <code>.js</code> React file types, the editor's user settings need to include:</strong></p>

<p>Open <code>Preferences: User Settings</code>  </p>

<pre><code>"emmet.syntaxProfiles": {
    "javascript": "jsx"
}
</code></pre>

<p>A simple fix, but man I'm so happy to have Emmet working again!</p>]]></description><link>http://duncanleung.com/emmet-for-jsx-on-js-files-visual-studio-code/</link><guid isPermaLink="false">1ac34b23-1e4a-45fe-928e-47d4866e42d4</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Tue, 24 Jan 2017 04:34:00 GMT</pubDate><content:encoded><![CDATA[<p><strong>To have Emmet recognize jsx in <code>.js</code> React file types, the editor's user settings need to include:</strong></p>

<p>Open <code>Preferences: User Settings</code>  </p>

<pre><code>"emmet.syntaxProfiles": {
    "javascript": "jsx"
}
</code></pre>

<p>A simple fix, but man I'm so happy to have Emmet working again!</p>]]></content:encoded></item><item><title><![CDATA[React.js - Understanding Props and State for Component Composition]]></title><description><![CDATA[<p>Another quick brain dump on my notes about React's <code>props</code> and <code>state</code>.</p>

<p>Understanding the different use cases for each allows for clear data management and a clean pattern when thinking about React component composition by creating <strong><em>Controller Views</em></strong> and 'dumb' <strong><em>Presentation Components</em></strong>.</p>

<h6 id="propsandstate">Props and State</h6>

<p>Data for React components are</p>]]></description><link>http://duncanleung.com/react-understanding-props-and-state/</link><guid isPermaLink="false">47209569-60b5-495b-9e36-69d61aad9756</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Thu, 05 Jan 2017 08:00:14 GMT</pubDate><content:encoded><![CDATA[<p>Another quick brain dump on my notes about React's <code>props</code> and <code>state</code>.</p>

<p>Understanding the different use cases for each allows for clear data management and a clean pattern when thinking about React component composition by creating <strong><em>Controller Views</em></strong> and 'dumb' <strong><em>Presentation Components</em></strong>.</p>

<h6 id="propsandstate">Props and State</h6>

<p>Data for React components are stored as <code>props</code> and <code>state</code></p>

<hr>

<h4 id="reactprops">React <code>props</code></h4>

<pre><code>var UserForm = React.createClass({  
    getDefaultProps: function() {
        return {
            name: 'fullname',
            placeholder: 'Enter your name',
            value: ''
        };
    },
    render: function() {
        return (
            &lt;CustomInput type="text"
               name={this.props.name}
               className="form-control"
               placeholder={this.props.placeholder}
               value={this.props.value}
               onChange={this.props.onChange}
            /&gt;
        );
    }
});
</code></pre>

<ul>
<li><code>props</code> (aka. properties) are references to parameters that are passed down from parent components.</li>
<li>The data is owned by the parent so <code>prop</code> data is immutable within the child component.</li>
<li><code>props</code> facilitates uni-directional data-flow from parent to child components.</li>
</ul>

<h5 id="getdefaultprops"><code>getDefaultProps</code></h5>

<ul>
<li>If the parent component doesn't declare value, you can set default <code>props</code> with <code>getDefaultProps</code>.</li>
</ul>

<h5 id="propvalidation"><code>prop</code> Validation</h5>

<p><code>props</code> can be validated through <code>React.PropTypes</code>, though it only runs in development environment of React. (By default, minified version of React runs in production mode.)</p>

<p><code>React.PropTypes</code> allows setting explicit expectations about the expected data type for a component's props. It's a good way to debug, but since it only runs in dev environment, it's shouldn't be used in production to validate <code>props</code>.</p>

<p><strong>Note:</strong> <code>props</code> that aren't required should have a default prop defined with <code>getDefaultProps</code></p>

<p><strong>Use <code>React.PropTypes</code> to Specify type: number, string, bool, etc.</strong></p>

<pre><code>React.PropTypes.array  
React.PropTypes.bool  
React.PropTypes.func  
React.PropTypes.number  
React.PropTypes.object  
React.PropTypes.string  
</code></pre>

<p><strong><code>propTypes</code>: Maps a validation function for each prop</strong></p>

<pre><code>propTypes: {  
    author: React.PropTypes.object.isRequired,
    onSave: React.PropTypes.func.isRequired,
    validate: React.PropTypes.func.isRequired,
    errors: React.PropTypes.object,
    hasErrors: React.PropTypes.func.isRequired
}
</code></pre>

<hr>

<h5 id="reactstate">React <code>state</code></h5>

<pre><code>var ManageAuthors = React.createClass({  
    getInitialState: function() {
        return {
            author: { id: '', firstName: '', lastName: '' }
        };
    },
    render: function() {
        return (
           &lt;AuthorForm
            author={this.state.author}
            //onChange, run this.setAuthorState function
            onChange={this.setAuthorState}
            onSave={this.saveAuthor}
           /&gt;
        );
    }
});
</code></pre>

<ul>
<li><code>state</code> should be used in controller views (the top level component). This allows separating logic from Presentation Component markup.</li>
<li><code>state</code> data is owned by the component so <code>state</code> is mutable data.</li>
<li><code>state</code> is passed down to nested child components as immutable data via <code>props</code>.</li>
</ul>

<h5 id="getinitialstate"><code>getInitialState</code></h5>

<ul>
<li>Typically only used to set default <code>state</code> in the top level (controller view) component.</li>
</ul>

<hr>

<h4 id="componentcompositioncontrollerviews">Component Composition - Controller Views</h4>

<p>A <strong><em>Controller View</em></strong> is a convention to have a single, top level view that:</p>

<ul>
<li>Owns <code>state</code> data</li>
<li>Interacts with any stores</li>
<li>Passes data down to children via <code>props</code>.</li>
</ul>

<p>Setting up and thinking about Controller View component composition allows for cleaner data management:</p>

<ul>
<li>Provides a single, logical place to interact with Flux/Redux stores.</li>
<li>Always know where data is coming from and where the source of truth is.</li>
<li>Data flow is controlled for all child component by setting <code>props</code> on children components.</li>
</ul>

<p>I'll follow up with another post on component creation techniques to talk more about <strong><em>Controller Views</em></strong> and <strong><em>Presentation Components</em></strong>.</p>]]></content:encoded></item><item><title><![CDATA[React.js - When To Use Each Lifecycle Method]]></title><description><![CDATA[<p>Just a quick brain dump of my notes on React's lifecycle methods.</p>

<hr>

<h2 id="mounting">Mounting</h2>

<h3 id="componentwillmount"><code>componentWillMount</code></h3>

<p><strong>When does it hook:</strong></p>

<ul>
<li>Before initial render, both client and server (DOM does not exist yet).</li>
</ul>

<p><strong>What situations to use it:</strong></p>

<ul>
<li>Provides a way to set the component's initial <code>state</code>.</li>
</ul>

<h3 id="componentdidmount"><code>componentDidMount</code></h3>

<p><strong>When does it hook:</strong></p>

<ul>
<li>After</li></ul>]]></description><link>http://duncanleung.com/react-when-to-use-lifecycle-methods/</link><guid isPermaLink="false">3ff3984e-c0d4-496a-82c8-d8fa62e160c4</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Fri, 16 Dec 2016 15:20:08 GMT</pubDate><content:encoded><![CDATA[<p>Just a quick brain dump of my notes on React's lifecycle methods.</p>

<hr>

<h2 id="mounting">Mounting</h2>

<h3 id="componentwillmount"><code>componentWillMount</code></h3>

<p><strong>When does it hook:</strong></p>

<ul>
<li>Before initial render, both client and server (DOM does not exist yet).</li>
</ul>

<p><strong>What situations to use it:</strong></p>

<ul>
<li>Provides a way to set the component's initial <code>state</code>.</li>
</ul>

<h3 id="componentdidmount"><code>componentDidMount</code></h3>

<p><strong>When does it hook:</strong></p>

<ul>
<li>After the DOM has rendered.</li>
<li>Both the DOM and component have rendered when this function is called.</li>
</ul>

<p><strong>What situations to use it</strong></p>

<ul>
<li>When access to the DOM is needed.</li>
<li>A good place to set timers, AJAX requests.</li>
</ul>

<hr>

<h2 id="updating">Updating</h2>

<p>These lifecyle methods will occur when parents change properties and then <code>setState</code>.</p>

<h3 id="componentwillreceiveprops"><code>componentWillReceiveProps</code></h3>

<p><strong>When does it hook:</strong></p>

<ul>
<li>Runs just before new <code>props</code> are received.</li>
<li><strong>Note:</strong> <code>componentWillReceiveProps</code> is <strong>not</strong> called on initial render.</li>
</ul>

<p><strong>What situations to use it:</strong></p>

<ul>
<li>Use it when props have changed and to <code>setState</code> before the component re-renders.</li>
</ul>

<h3 id="shouldcomponentupdate"><code>shouldComponentUpdate</code></h3>

<p><strong>When does it hook:</strong></p>

<ul>
<li>Runs before render and when new <code>props</code> or <code>state</code> are being received.</li>
<li><strong>Note:</strong> <code>shouldComponentUpdate</code> is <strong>not</strong> called on initial render.</li>
</ul>

<p><strong>What situations to use it:</strong></p>

<ul>
<li>Use it to tweak the app's performance.</li>
<li>Sometimes <code>props</code> and <code>state</code> changes, but the component doesn't need to rerender (when it doesn't affect the DOM).</li>
<li><code>Return false</code> to void unnecessary re-renders.</li>
</ul>

<h3 id="componentwillupdate"><code>componentWillUpdate</code></h3>

<p><strong>When does it hook:</strong></p>

<ul>
<li>Immediately before rendering the component, after <code>props</code> or <code>state</code> have been received.</li>
<li><strong>Note:</strong> <code>componentWillUpdate</code> is <strong>not</strong> called on initial render.</li>
</ul>

<p><strong>What situations to use it:</strong></p>

<ul>
<li>Prepare for a render update.</li>
<li><strong>Note:</strong> <code>setState</code> can't be called in this function.</li>
</ul>

<h3 id="componentdidupdate"><code>componentDidUpdate</code></h3>

<p><strong>When does it hook:</strong></p>

<ul>
<li>After component updates are rendered to the DOM.</li>
<li><strong>Note:</strong> <code>componentDidUpdate</code> is <strong>not</strong> called on initial render.</li>
</ul>

<p><strong>What situations to use it:</strong></p>

<ul>
<li>Now that the component has been rendered, operations on the DOM can be done here.</li>
<li>Any DOM manipulations after an update.</li>
</ul>

<hr>

<h2 id="unmounting">Unmounting</h2>

<h3 id="componentwillunmount"><code>componentWillUnmount</code></h3>

<p><strong>When does it hook:</strong></p>

<ul>
<li>Immediately before the component is removed from the DOM.</li>
</ul>

<p><strong>What situations to use it:</strong></p>

<ul>
<li>Cleanup of any event listeners etc.</li>
</ul>]]></content:encoded></item><item><title><![CDATA[Pub/Sub JavaScript Pattern]]></title><description><![CDATA[<p>I've been feeling pretty awesome refactoring my spaghetti code into modular code using the module and prototype patterns into my projects. But I still can't shake this 'dirty' feeling with how my code is written.</p>

<p>Although my code is now organized and modular, it still feels tangled and tightly coupled</p>]]></description><link>http://duncanleung.com/pub-sub-javascript-pattern/</link><guid isPermaLink="false">aefece81-a31c-471e-9532-cc15bbbda9d9</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Sun, 04 Dec 2016 06:29:08 GMT</pubDate><content:encoded><![CDATA[<p>I've been feeling pretty awesome refactoring my spaghetti code into modular code using the module and prototype patterns into my projects. But I still can't shake this 'dirty' feeling with how my code is written.</p>

<p>Although my code is now organized and modular, it still feels tangled and tightly coupled to many other portions of the codebase.</p>

<p>After a bit more reading I came across the Publish/Subscribe (Observer) pattern and this seems to be the answer to my problem.</p>

<p>Here's another JavaScript patterns brain dump.</p>

<p>So far I've been using Morgan Roderick's PubSubJS library to implement Pub/Sub communication in my code: <a href="https://github.com/mroderick/PubSubJS">https://github.com/mroderick/PubSubJS</a></p>

<h6 id="decouplingcode">Decoupling Code</h6>

<p>Code is tightly coupled when objects directly call the methods of other objects. Instead, the pub/sub pattern allows a dependent object to 'subscribe' to a specific event of another object and is notified when the event occurs.</p>

<p><strong>One of the main goals of the pub/sub pattern is to avoid dependencies between the subscriber and the publisher.</strong></p>

<p>Pub/Sub allows code to be decoupled and broken down into smaller, loosely coupled modules. When an event is published, a notify message is sent out. All the subscribed observers receive the message and can invoke their callbacks.</p>

<p><strong>Essentially, publishers notify subscribers when events occur.</strong></p>

<p><strong>Subscribers can listen to these notifications and execute code in response to the event</strong>.</p>

<h6 id="encouragingreusablemodules">Encouraging Reusable Modules</h6>

<p>With loosely coupled code, each component of the system is only concerned with it's own responsibility and doesn’t care directly about the logic of any other components.</p>

<p>This allows for easy reuse of different modules since modules are not directly coupled with the interfaces of other modules.</p>]]></content:encoded></item><item><title><![CDATA[Javascript Chaining Pattern]]></title><description><![CDATA[<p><img src="http://duncanleung.com/content/images/2016/11/javascript.png" width="100px"></p>

<p>I've always been intrigued by the chaining pattern that jQuery implements. It's such an elegant way to present an API: it's both concise, and readable.</p>

<pre><code>//Example
$('.foo')
    .addClass('bar')
    .html('hello world')
    .fadeIn('slow');
</code></pre>

<p>It turns out that the fundamentals of this pattern isn't that complicated.</p>

<p><em>(I'll update you</em></p>]]></description><link>http://duncanleung.com/javascript-chaining-pattern/</link><guid isPermaLink="false">2aedc7c1-d44a-4334-abb8-bb0206c74a59</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Fri, 18 Nov 2016 06:44:51 GMT</pubDate><content:encoded><![CDATA[<p><img src="http://duncanleung.com/content/images/2016/11/javascript.png" width="100px"></p>

<p>I've always been intrigued by the chaining pattern that jQuery implements. It's such an elegant way to present an API: it's both concise, and readable.</p>

<pre><code>//Example
$('.foo')
    .addClass('bar')
    .html('hello world')
    .fadeIn('slow');
</code></pre>

<p>It turns out that the fundamentals of this pattern isn't that complicated.</p>

<p><em>(I'll update you guys again when I actually try to implement it into my code... hah)</em></p>

<p>The main key to the chaining pattern involves <strong>returning the object at the end of each method</strong> using <code>return this</code>, which allows additional methods to be called on the object again.</p>

<p>I've written a short codepen to play around with this chaining pattern.</p>

<p data-height="592" data-theme-id="0" data-slug-hash="RooEaj" data-default-tab="js" data-user="duncanleung" data-embed-version="2" data-pen-title="JavaScript Chaining Pattern" class="codepen">See the Pen <a href="http://codepen.io/duncanleung/pen/RooEaj/">JavaScript Chaining Pattern</a> by Duncan (<a href="http://codepen.io/duncanleung">@duncanleung</a>) on <a href="http://codepen.io">CodePen</a>.</p>  

<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>]]></content:encoded></item><item><title><![CDATA[Caveat: Prototype Pattern 'Constructor' Link Overwrite]]></title><description><![CDATA[<p>During my fix to learn and implement Javascript design patterns, my OCD side noticed that there was a 'variation(?)' to the prototype pattern that I was seeing in some parts of our codebase.</p>

<p>For clarity sake, this is the textbook Prototype Pattern  </p>

<pre><code>// Constructor function to create Person objects
function</code></pre>]]></description><link>http://duncanleung.com/caveat-prototype-pattern-constructor-link-overwrite/</link><guid isPermaLink="false">2a0c6af0-b464-42fb-b227-0336a448cf50</guid><dc:creator><![CDATA[Duncan Leung]]></dc:creator><pubDate>Fri, 11 Nov 2016 07:44:26 GMT</pubDate><content:encoded><![CDATA[<p>During my fix to learn and implement Javascript design patterns, my OCD side noticed that there was a 'variation(?)' to the prototype pattern that I was seeing in some parts of our codebase.</p>

<p>For clarity sake, this is the textbook Prototype Pattern  </p>

<pre><code>// Constructor function to create Person objects
function Person(name, age, gender) {  
    this.name = name;
    this.age = age;
    this.gender = gender;
}

// Constructor prototype to share properties and methods
Person.prototype.sayName = function() {  
    console.log('My name is ', this.name);    
};

Person.prototype.sayAge = function() {  
    console.log('My age is ', this.age);
}
</code></pre>

<p>In our codebase, I was seeing a nice 'short-hand(?)' to declare methods on the prototype by assigning an object literal with the methods to <code>Person.prototype</code>.  </p>

<pre><code>// Constructor function to create Person objects
function Person(name, age, gender) {  
    this.name = name;
    this.age = age;
    this.gender = gender;
}

// Constructor prototype to share properties and methods
Person.prototype = {  
    this.sayName: function() {
        console.log('My name is ', this.name);    
    },

    this.sayAge = function() {
        console.log('My age is ', this.age);
    }
}
</code></pre>

<p>But something didn't sit right and I remembered reading about issues using this object literal short-hand.</p>

<h5 id="caveatyoureoverwritingtheprototypeobject">Caveat: You're Overwriting the Prototype Object!</h5>

<p>Say we've created a new <code>jim</code> object, from the <code>Person</code> constructor function.</p>

<pre><code>var jim = new Person('Jim', 12, 'Male');  
</code></pre>

<p>The caveat with using the short-hand variation of the prototype pattern occurs when you try to call the <code>jim.constructor</code> property. You would expect <code>jim.constructor</code> to point to the <code>Person</code> constructor function. Instead, it points to the <code>function Object {...}</code> constructor function. What?</p>

<p>The fix is to explicitly declare the constructor property on <code>Person.prototype</code> when using the object literal assignment to the function's prototype.</p>

<pre><code>Person.prototype = {  
    constructor: Person,

    .... //other methods
}
</code></pre>

<h5 id="prototypechainwhatshappeninginthebackground">Prototype Chain: What's Happening In the Background</h5>

<p>When you define a function, a prototype object (example: <code>Person.prototype</code> for the constructor function) is automatically created with a default property <code>Person.prototype.constructor</code> which points to the constructor function.</p>

<p>All new objects created from <code>Person</code> can access and reference the <code>Person</code> constructor function via the prototype chain, which delegates to <code>Person.prototype.constructor</code>.</p>

<p>1: <code>Person</code> constructor function is created.  </p>

<pre><code>var Person = function () {...}  
</code></pre>

<p>2: <code>Person.prototype</code> object is automatically created with a default property, <code>constructor</code>.  </p>

<pre><code>Person.prototype = {  
    constructor: Person
}
</code></pre>

<p>3: A new object <code>jim</code> is instantiated from <code>Person</code>. The object <code>jim</code> is automatically linked to <code>Person.prototype</code> via the prototype chain.</p>

<p>Note: <code>jim.hasOwnProperty('constructor') //false</code>  </p>

<pre><code>var jim = new Person('Jim', 12, 'Male');  
</code></pre>

<p>4: Calling <code>jim.constructor</code> actually calls <code>Person.prototype.constructor</code> via the prototype chain.  </p>

<pre><code>Person.prototype = {  
    constructor: Person
}
</code></pre>

<p>5: However, if Person.prototype is overwritten, <code>Person.prototype.hasOwnProperty('constructor')</code> is now false! The call then delegates further up the prototype chain to the base <code>Object</code> constructor function.</p>

<p>This is why we were seeing <code>jim.constructor</code> pointing to the <code>function Object {...}</code> constructor function.</p>

<p>So, using an object literal to define the methods on <code>Person.prototype</code>, actually overwrites the object.</p>

<p>To allow instantiated objects to reference the constructor function, the property <code>Person.prototype.constructor</code> needs to be manually declared.</p>]]></content:encoded></item></channel></rss>