React + Reflux and how to boost your development workflow

F73efb403456806e5ffebdc09a3967ee?s=47 Roy Yu
October 03, 2015

React + Reflux and how to boost your development workflow

This presentation we will be going through a few latest technology in web development trend. React, Reflux, Gulp and Webpack.

If you are interested, here is the github link to play with the technologies in this slide. https://github.com/iroy2000/react-reflux-boilerplate-with-webpack

"React Reflux Workflow Boilerplate" is a workflow framework that make life easier for developers by providing a development and production ready build process framework out of the box.

Original description in SVCC 2015
============================
In this session, we will walk through some features of React and Reflux ( refactor of Flux ), and the goal is, at the end of the session, you will have enough knowledge to start your React + Reflux journey. We will also cover some tools, for example Gulp and other technologies, and explain how those technologies can make your life as a developer thousand times easier during development or even production build process. During demo session, we will show case a workflow boilerplate I created a while ago in which all attendants will get benefit from, and the boilerplate would possible make you a super star in your workplace with just a few simple commands ~

F73efb403456806e5ffebdc09a3967ee?s=128

Roy Yu

October 03, 2015
Tweet

Transcript

  1. React + Reflux And how to boost your development workflow

    Roy Yu Silicon Valley Code Camp ‘15
  2. About Me

  3. About Me If you are already comfortable with the technology

    in today’s presentation, you can check this out and play around with it as well. Don’t forget to give it a star \o/ React Reflux Workflow Boilerplate https://github.com/iroy2000/react-reflux-boilerplate-with- webpack
  4. React

  5. React •  A JS library that pitches different idea on

    how to build User Interface •  Simplicity over familiarity •  Unidirectional data flow •  Virtual DOM concept
  6. React •  It is not a MV* framework that you

    see in the market today. •  If you are coming from other Javascript framework, React does NOT have :- •  Controllers •  Templates •  Models •  Global Event Listeners
  7. React All React cares about is Component. It is also

    usually consider a “View”. And since it doesn’t have assumption of your current technology stack, it is fairly easy to mix into your current project.
  8. React •  React has a optional syntax component called JSX

    •  And we will use JSX in our presentation today •  And with JSX, you can bundle javascript and HTML to make your component easy to understand.
  9. React •  React has a optional syntax component called JSX

    •  And we will use JSX in our presentation today •  And with JSX, you can bundle javascript and HTML to make your component easy to understand.
  10. React •  React has a optional syntax component called JSX

    •  And we will use JSX in our presentation today •  And with JSX, you can bundle javascript and HTML to make your component easy to understand.
  11. React OK Here now comes your first React component !!

  12. React BUT Let me explain in one slide of basic

    React Syntax ~
  13. React •  Everything in React is a component and it

    is invoked with React.createClass() •  And when develop a component, you must have at least a function called render() •  This function means what to output ( print )
  14. React Yes, so cool ! \o/

  15. React O… HTML? /O\

  16. React •  The html mark up above is NOT a

    real html markup … •  It is something called “JSX” ( a.k.a JavaScript XML ) that FB build as a React syntax extension. •  JSX is a sugar syntax of pure javascript data structures.
  17. React It will eventually transformed into native JS code You

    can write your React component without JSX, but it just makes your life much easier J
  18. React •  Developing JSX is almost the same as writing

    HTML / XML.
  19. React {} is for evaluating a javascript variables or expressions.

    Passing attributes to other component. You can pass in callback as properties to other component. Custom tag means a component
  20. React •  Before showing you some demo, there are a

    few concepts you need to understand in React …
  21. React •  life cycle methods means at some special moments

    in the application, React gives developers some methods / hooks to inject code before and after those moments. •  Each React component has a few life cycle methods, the most basic one are the followings :- •  componentWillMount() •  componentDidMount() •  componentWillUnmount() •  Mount means attach to a DOM, so the above functions mean “What should a component do before / after attaching to a DOM” •  Unmount means unattach from a DOM, it means “What should a component do when it unattach from a DOM”
  22. React •  React component has concept of “States and Properties”

    :- •  States are mutable data and usually changed because of user inputs or interactions. You can consider “states” as underlying model of a “View”. Because when states changes, React will call “render” function. ( stateful component ) •  Properties ( props ), on the other hand, are immutable data and mostly for display purpose. ( stateless component )
  23. React Why does React has States and Props ? • 

    In React theory, we want to keep most of our component as “stateless”, which will decrease the complexity of our application. •  A common pattern is have a component up in hierarchy to own the states and pass those as properties to “child components” •  And the parent component can also pass in a callback to children and give it a option to notify the parent if the state should change.
  24. React Props •  getDefaultProps() // plural •  Inside your component,

    you can access it with •  this.props.your_item_key States •  getInitialState() // singular •  setState() •  Inside your component, you can access it with •  this.state.your_item_key •  When you call setState(), it will render the corresponding component.
  25. React Mixins It is not a concept of React, but

    it is more like a design pattern in javascript. The purpose of mixin is enabling different javascript components to share common functionalities / behavior by abstracting those common code into a Mixin. And React makes it a standard pattern in its framework and provides a “mixins” keyword for that. You will see that a lot if you develop a more complicated React application.
  26. React Last few tips before DEMO •  React component communication

    is very close to our DOM interaction nowadays --- Events flow up, Data flows down. This is the gist of unidirectional data flow, your data only flows one way, but your event can bubble up. Don’t worry if you don’t understand it today, just remember the red text above and it is for reducing complexity J
  27. React •  Few of the benefits of using React is

    to make the components :- •  Reusable •  Composable •  Unit Testable •  Easier to Maintain •  Reducing Complexity Making sure your component is self contained. Well, while it’s all true, developers can still create a mess without a doubt if it is not used correctly …
  28. React •  React maintains a in memory representation of DOM

    ( They called it Virtual DOM ). •  Whenever the function render() is called, it will return that Virtual DOM “representations”. •  And it will go through a diff algorithm to compute the fastest way to update the real DOM. •  And it is very fast based on benchmark, because your component doesn’t interact with real DOM directly.
  29. React •  Live Demo of React

  30. React And when you start digging deeper into React, few

    questions might help you along the way :- •  How do I break out my component to be self contained ? •  How to isolate my states in a few components, so that the rest of the components can be as “stateless” as possible ? •  Whom should own the states ?
  31. React What we’ve covered today in React are pretty basic

    concepts, you can do some research later on the following topics :- •  React Router ( a routing system for React ) •  React Addon ( some useful utilities to help very specific use cases )
  32. React •  While everything with ReactJS is good within a

    small application, but once your project size getting larger, you'll run into issues about handling data. •  In fact, ReactJS doesn't really care how the data gets passed in or how that data should be handled across the web application.
  33. React •  Some developers try to use React to replace

    the View of their Backbone applications; while others try to inject React into their own frontend stack. •  And today I’m going to pitch another library that work very well with React’s unidirectional dataflow concept.
  34. Reflux •  Reflux – an Refactor of Flux

  35. Reflux •  Before Reflux, let’s talk about Flux a little

    bit •  What is Flux? An application architecture created by Facebook to build client side web applications to have a single data flow pattern.
  36. Reflux •  What problem they are trying to solve ??

  37. Reflux Javascript communication is async, how can you guarantee the

    View will always be the same state everytime ?? In order words, how to make our application more predictable.
  38. Reflux What is Flux?

  39. Reflux What the Flux?

  40. Reflux •  All data flows through the dispatcher as a

    central hub. •  Store usually holds the application's data and business logic.
  41. Reflux •  When a user interacts with a React view,

    the view sends an action (usually represented as a JavaScript object with some fields) through the dispatcher. •  The dispatcher then invokes the callbacks that the stores have registered with it.
  42. Reflux •  When the store triggers an update, it emits

    a change event to signal the view that a change to the data layer has occurred. •  View listens for these Store events and retrieve data from the store through an event handler. Then the views call their own setState() method, causing a re-rendering of themselves.
  43. Reflux Reflux – an Refactor of Flux Actions is the

    only agent between View and Store.
  44. Reflux •  The pattern is composed of actions and data

    stores, where actions initiate data to flow through store before going back to the view. •  View can signal the store through actions. •  The data flow is still unidirectional. •  Dispatcher is removed and let actions to act as dispatcher instead.
  45. Reflux Let’s take a simple real world example ~ How

    about a shopping Cart Demo ?
  46. Reflux

  47. Reflux Let’s say user triggers an action from View

  48. Reflux Actions Store View

  49. Reflux Let’s go to some Reflux basic syntax ~ But

    before that, let me show you some example code first.
  50. Reflux Creating Action

  51. Reflux

  52. Reflux Action Hooks Reflux comes with two hooks for each

    of the actions •  preEmit •  Before an action emitting an event, what it should do •  It receives the arguments from action when the action is invoked •  shouldEmit •  Should the event be emitting event at all, by default it returns true •  And when it returns false, the event won’t be emitted
  53. None
  54. Reflux Extending Reflux Actions •  If you want to extend

    Reflux with a common set of methods, you can use Reflux.ActionMethods. It means all your actions will mix in with those methods.
  55. Creating Store

  56. None
  57. Reflux •  Important: When Store trigger() function is called, it

    will pass the flow / data to its listener(s), for example, your React Component. By default, when the state change, your View (React Component) will re-render. •  Let’s look at that again J
  58. Store use trigger() to pass data to its listeners.

  59. Reflux •  Store can listen to Actions and perform some

    operations •  Store has an init() function that you can bind listeners •  For example, the above just says that •  When greetingAction emits an event, the Store’s getUserByEmail() function will get called
  60. Reflux •  But since this way of init binding pattern

    is so frequent that Reflux.Store actually has a “listenable” shorthand to make our life easier.
  61. Reflux

  62. Reflux •  You define and call your actions as usual

    •  But your store will need to add a “listenables” with what Action class you want to mix in. For example, we mix in “ExampleActions” in our case.
  63. Reflux •  And you need to name your Store methods

    accordingly based on your action name, both of the following will the the same :- •  onGreet() or greet() ß see the first letter is capitalized ?! •  But as personal best practice, it is better to do onAction to indicate that the method is an event handler
  64. Reflux •  Now we have Actions and Store, and the

    next question is how my React Component listen to any changes to the Store ?
  65. Reflux •  Reflux provides a Reflux.ListenerMixin, which will give your

    Component a few “listening” methods. For example :- •  listenTo •  listenToMany If you are curious of what listenTo is doing, it is essentially just calling the call back of the listenable. listenTo: function(listenable, callback, defaultCallback ) { //… } Note: listenable could be an Action or a Store
  66. None
  67. Reflux •  There are two more more Reflux convenient mixins

    that make certain use case even easier •  Reflux.connect •  Reflux.connectFilter
  68. None
  69. Reflux •  Reflux.connectFilter works the same as Reflux.connect, but it

    only returns a filtered results before update the component state. •  If you are curious, you just need pass in a callback as the 3rd parameter that do the filtering work. •  Actually it is the same as you filter the data inside your Store and send the data back to the listeners. I usually using lodash or underscore to do the filtering.
  70. Reflux •  Store can listen to another Store, syntax is

    the same as a View listening to the Store. •  This feature is helpful ONLY if you want to do some transformations for your data. Don’t abuse it ~
  71. None
  72. Reflux Lastly … •  Just as Actions, Store also has

    storeMethods, where you want all your Stores has the same set of methods available. •  Store supports “mixins” keyword, just as a React component.
  73. Reflux Lastly … •  Just as Actions, Store also has

    storeMethods, where you want all your Stores has the same set of methods available. •  Store supports “mixins” keyword, just as a React component.
  74. That’s it about the basic React + Reflux The next

    section is show you how to build on top
  75. That’s it about the basic React + Reflux The next

    section is show you how to build on top And become a Rock Star
  76. Gulp

  77. What is Gulp ? •  Gulp is an automate task

    runner or a build system, written in node.js •  Gulp allows you to input your source file, pipe them through plugins and get the final product at the end
  78. What is a build system ?

  79. What is a build system ? It should take care

    of your repetitive tasks •  Concatenating Javascript •  Prefixing CSS
  80. What is a build system ? It consumes utilities /

    plugins to fulfill its task •  JSHint •  Uglify Javascript •  Compile JSX •  … etc
  81. What is a build system ? In Gulp, you can

    also define task to •  Start a local server •  Integrate Live Reload feature •  Deploy your script into destination
  82. What is a build system ? Looks like some of

    you are still very confused, try to imagine a factory ~
  83. What is a build system ?

  84. What is a build system ? It transforms assets or

    resources into consumable state. Image a car factory’s process of transforming “glasses”, “metal”, “plastic”, “leather”, “carbon fiber” … etc into a car, and then going through testing process, anti crash test before shipping to car dealers. ( The process of car factory will be more complicated, this is a metaphor only )
  85. Why do I need it ? If it used correctly,

    it could provide benefits on •  Page performance in automated fashion •  Image optimization •  JS minification •  Html minification •  Font optimization •  … all in automated fashion How many of you still manually copy your JS code and minified it in an online service and manually deploy / ftp to your server ??
  86. Why do I need it ? If it used correctly,

    it could also provide benefits on •  Developing seamless development workflow •  Live update your in your browser when you make changes to your code. •  Run test automatically whenever your JS file changes •  Give you fast feedback when your code doesn’t work •  … etc How many of you still manually reload your browser when you make code changes ?
  87. Why do I need it ? •  In short, it

    is recommended for large projects •  Save Time, Save Money and Get Smarter ~
  88. Gulp Basics •  Before we start, it will be relatively

    easy for you to understand Gulp if you have basic knowledge of the following technologies. •  The only must have knowledge to use Gulp is Javascript.
  89. Gulp Basics In order to achieve all we’ve mentioned previously

    •  Gulp is heavily relying on Plugins to extend its functionality •  You can easily combine different plugins to achieve complicated task
  90. Gulp Basics •  And this is important!! You should search

    for available plugins in Gulp site plugin section ( the most recommended way ).
  91. Gulp Basics

  92. Gulp Basics •  Gulp use Streams to link plugins together.

    It turns out that this way makes Gulp blazingly fast ( compare to its competitor ) by minimizing I/O and temporary files.
  93. Gulp Basics •  Gulp provides a programmable interface to define

    your task. And tasks are how you control Gulp, we will cover later with example. •  Task can interact with both plugins and streams.
  94. Installation •  You must have npm installed, and run the

    following commands :- •  $> npm install –g gulp •  $> npm install –save-dev gulp Yes, you have to install gulp globally and as a project dependencies.
  95. Gulp Basics •  Create a new working directory •  Create

    a file called “gulpfile.js” •  The “gulpfile.js” is where you define all your task, and you tell Gulp when to run those tasks // gulpfile.js var gulp = require(‘gulp’); gulp.task(‘minify-css’, function() { // place your code of css task here });
  96. Gulp Basics •  gulpfile.js – it tells gulp what are

    the tasks and when to run the task.
  97. Gulp Basics Gulp provides several simple interfaces for you to

    write tasks with. •  task // define a task •  src // where is the source file •  pipe // how you want to transform your src files •  dest // where to write your transformed files •  watch // watch files and do something when file changes
  98. Gulp Example

  99. Gulp Example

  100. Gulp Example

  101. Gulp Example

  102. Gulp Note •  Task can just be a list of

    task •  Task can have dependencies
  103. Gulp Note •  Remember that all the path are relative

    to your gulpfile.js •  Remember that Gulp is using node.js, and you can do whatever you can do in node.js inside gulpfile.js
  104. •  OK! Now you know the secret of Gulp …

  105. •  And at this point, you may have the following

    feeling ~
  106. None
  107. •  You think you can do anything now ~

  108. •  But wait …

  109. Problems Today •  When we are building large application, especially

    the case of Single Page Application ( SPA ) •  So many HTTP request because of various resources •  Affecting our page rendering time •  While our application get less and less page reload nowadays, but that means more and more javascript code inside our page ( thick client ).
  110. Problems Today •  Even with today’s best practice in the

    industry, we could only make the problems less obvious, but we didn’t really solve it. •  And at some point, all of us will be facing the following problems :- •  Minimizing File Size v.s. Minimizing HTTP Request •  How to package our application and resources and serve to user as fast as possible •  How to make our code more modularity and easier to maintain
  111. Problems Today •  We have introduced Gulp earlier, which helped

    us to use industry best practices, for example, minify JS, minify HTML, optimize images … etc. But … •  Still generating a giant JS script at the end •  Images, CSS has still need to take extra http request •  It doesn’t understand the dependencies of the resources •  It doesn’t know how to do on demand ( async ) load ( out of the box ) •  What about our css, scss, images, coffeescript … etc, why only we have modularity in Javascript ?
  112. Webpack

  113. What is Webpack •  Webpack is … •  A module

    bundler •  It treats all frontend assets as modules •  Yes, including .coffee, sass, jsx, css, images, fonts .. etc •  Thus, it understands all the dependencies of your application ( Dependency Graph ) •  So in short, it takes all your dependencies and generates static assets.
  114. What is Webpack

  115. What is Webpack What does that graph mean ? • 

    Everything is a module •  Module could have dependencies •  And webpack can turn all module with dependencies and transform it into static assets •  Yes, transform means taking your assets as input, do something for your assets and return output assets. Oh, wait !! We see the word “transform” again … Is that sound familiar ??
  116. What is Webpack •  How does Gulp different from Webpack

    ?
  117. What is Webpack •  Webpack ecosystem is very similar to

    Gulp, it depends heavily on its “loaders” ( Gulp called it “Plugins” ) to transform resources •  Webpack with loaders can do things that Gulp can do •  Webpack can do more than Gulp ( will cover that ) •  Some people actually replaces Gulp and browsify all together with Webpack.
  118. What is Webpack Yes, Webpack can do more J • 

    Supports code splitting •  Supports generating artifacts for multiple entry point application •  While it has loaders for assets transformation, it also has plugin to alter out of the box webpack behavior •  It also comes with a DEV tool to make development life easier
  119. What is Webpack Code Splitting ( Just for reference of

    previous slide ) In the market, there are solutions to request each js modules dynamically or compile all those resources as a giant js file. The “request per module” approach involves too many http requests; while the “all in one” approach will have you download all the code you don’t need. But webpack is trying to be more flexible by combining related modules into logical page scope “Chunks”. For example, in your SPA, when you hit /#/tutor/123 and /#/book/123 are different “logical page”, and when you visit a particular url route, you should get only what you need for your logical page.
  120. What is Webpack •  Some of you may say …

    •  Oh man, why are you showing us Gulp then? •  Well … •  While Webpack has very neat feature, it is focusing on module bundling and transformation •  And Gulp is defining a workflow and what task to run at what time •  They could work pretty well together
  121. What is Webpack Let me give you a quick demo,

    because it could get confusing if I don’t do so … And after that, we will go back to the concept of Webpack ~
  122. What is Webpack Webpack •  Understands both CommonJS / AMD

    style ( So it means you can easily convert your current application to use with Webpack ) •  We will be CommonJS syntax today ( If you don’t know what that is, it is a module format for your JS file. )
  123. What is Webpack Webpack •  Relies heavily on plugins and

    loaders. Loaders are mostly for pre-processing files / static assets. Plugins are extending the webpack itself ( Many of webpack internals are essentially plugins ) •  For example, webpack don’t understand how to transform a coffee script unless we include a coffee script loader to handle it.
  124. What is Webpack Webpack •  Read a file call “webpack.config.js”

    to configure your webpack behavior. •  The rough idea of what this file will include :- •  Tell webpack where is your application JS entry point •  Tell webpack where you want your final transformed file to be output at •  Tell webpack what loaders you need to take care of your file •  Tell webpack if you want webpack to have any extra behavior by adding plugins.
  125. What is Webpack Let’s look at a basic example of

    webpack.config.js
  126. None
  127. What is Webpack Let’s strip it down …

  128. •  Tell webpack where is your application JS entry point

    •  Tell webpack where you want the final artifacts to be output at •  Tell webpack what loaders you need to take care of your file •  Tell webpack what extra behavior it should have by adding plugins.
  129. What is Webpack And in order to use Webpack, it

    means you need to learn how to configure webpack. Let’s go through some basic configuration ~
  130. What is Webpack { test // finding the file that

    match the regular expression loader // how to handle that file type exclude // exclude the search from this list ( optional ) } •  Loader transforms your resources •  Loader can be chained with ‘!’ •  Loader accept query parameter to pass configuration to the loader •  Loader at the end will return javascript •  Loader runs in Node.js and most of the loaders are available through npm
  131. What is Webpack Unlike Loaders, Plugins work on entire bundle

    instead of individual files Plugins usually can be installed via npm
  132. What is Webpack •  We talk about Code Splitting feature

    in Webpack earlier, to get a little deeper, code splitting is able to 1.  Extract common code into shared chunk 2.  Split code into on demand loaded chunk
  133. What is Webpack Extract common code into shared chunk • 

    Let’s say you have vendor code and application code. In your entry section, tell Webpack what to split out In plugins section, tell Webpack to take all the vendors related code out and make it as its own package
  134. What is Webpack Split code into on demand loaded chunk

    ( Lazy Loading ) •  If you have used requireJS before, it is almost the same syntax. Basic Syntax require.ensure([], function() { var MyModule = require(‘./MyModule’); /* … */ });
  135. What is Webpack Note: You do not need to define

    anything in Webpack configuration, Webpack knows your dependencies and understand lazy loading when analyzing your code.
  136. What is Webpack •  There are chances that you application

    will have two different entry points, for example, you application can contain user normal site and an admin user portal. •  Or when your application has different user experience in desktop and mobile and you want to serve different “application” to different platform. •  And Webpack is capable of creating multiple entry points for this kind of purpose.
  137. Multiple Entry Points Remember our webpack entry point config in

    the webpack.config.js ?? In order to create another entry, you simply go to that entry and add the entry point in order to create that.
  138. Multiple Entry Points And from now on when you generate

    the assets, you will have 3 different files. One is “main”, one is “admin” and one is “vendors”.
  139. What is Webpack Make sure you don’t mix up the

    concept of “Lazy Loading” and “Multiple Entry Points”. “Lazy Loading” are loading modules, and “Entry Point” is the highest part of your application. Webpack will generate a run time for Entry Points, and “Lazy Loading” are just barely modules and is for inclusion only.
  140. What is Webpack Webpack also comes with a live reload

    dev server, what it means if when you change your frontend assets ( any point from your application ), it will start a live reload without any user reload the browser. It is a pretty neat feature. I will show you in demo as well. Also, the configuration is in the git repo I show you at the beginning of this slides.
  141. What is Webpack The first green line: Make dev server

    available at http://localhost:8080/webpack-dev-server/ The second green line: Include hot reload functionality for your dev server
  142. What is Webpack •  Webpack also has an analyzing tool

    J
  143. What is Webpack •  Demo

  144. What is Webpack •  Any Questions ?

  145. Thank You You can reach me @ •  https://www.linkedin.com/in/iroy2000 React

    Reflux Workflow Boilerplate https://github.com/iroy2000/react-reflux-boilerplate-with- webpack