Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ReactRally: Migrating Critical Apps to React

ReactRally: Migrating Critical Apps to React

Jamis Charles

August 25, 2015
Tweet

More Decks by Jamis Charles

Other Decks in Programming

Transcript

  1. UI Engineer Send Money I’ve been at PP for 14

    months. I’ll be talking about lessons learned when we starting to gradually move to React.
  2. 2014 In 2014 when I joined the team, the Send

    Money flow looked like this…
  3. C++ XML Markup C++ on the Server side, and custom

    XML Markup on the client. Our team’s charge was to build & roll out the new Send Money experience, which looked like this…
  4. Server {Dust.js} Client Kraken.js BB We were now on a

    modern stack with Kraken.js/node on server, and Require.js, BB, and Dust.js for templating on the client. We’d ramped to 5% in the US when I joined. In the coming months we ramped to 100% in US. Things worked well for a while. We liked that Dust allowed us to use same template on the Server and the client. This came in handy when we moved from a server app to an SPA. Stack worked well for a while… Until our team had a hackathon to improve how fast the flow felt.
  5. As we started ramping up this new flow, we now

    had to support two flows that had different Views and templates, but shared a lot of common model logic. This became very ugly very fast.
  6. • too many abstraction layers • low confidence • difficult

    state bugs (currency codes mismatched etc) Pain Some of the pain we felt was… State bugs happened especially as you would navigate back and forth in the flow.
  7. Lets look at the abstraction layer problem. Say we want

    to change the AUD value in this list to AUY.
  8. Template.dust -> BB_view.js -> BB_model.js -> Route -> Node_controller ->

    Node_model -> Service API (SEVEN LAYERS) This feels like swimming upstream in order to find where this state is coming from. SEVEN LAYERS. This is crazy. Each of these jumps is a gap that you can fall into and get lost.
  9. This is a very poor DX. Really bad state to

    be in. But we have to balance this pain with the fact that we have…
  10. 100 million users in more than 100 countries We have

    100M users in over 100 countries. We can’t just up and change stacks and break things whenever we want to. We have to be responsible and have the appropriate amount of rigor. So what to do? We started exploring other options.
  11. We started looking at Ember. We really liked how opinionated

    it was. It provided a lot of structure that our app was missing. React looked really interesting as well, but we just didn’t know enough about it yet. We experimented a little bit with Ember. And then we started seeing tweets about Ember from somebody in the community. I’ve blurred out the name to protect his identity.
  12. We had looked at Ember. Now we wanted to look

    at react. ReactConf came along several weeks later. At this point we’d done our homework with React. We’d done some research. We’d hacked together a few proof of concepts. We were thinking about sending a few devs to EmberConf or to ReactConf. The reality was, that ReactConf came first, so we went there.
  13. ReactConf 5 of us went to ReactConf. It was really

    exciting. We were most excited by the fact that Facebook had had a lot of the same problems we were currently having and it seemed that React was solving these problems for them. We loved the focus on functional styles and principles. We realized that these principles would likely solve most of our problems. We completely bought into the ideas behind react. SIMPLIFY state. Immutable data. Functional principles. We could start doing these now. LETS TRY REACT!!!
  14. Gaining momentum In a big org, it can take a

    lot to change things. We sat down and looked at what needed to happen. Immediately we identified our biggest blocker…
  15. # note_en-US.properties note.title=Add a note note.placeholder=You can enter a note

    here. # note_de-DE.properties note.title=Notiz note.placeholder=Bitte schreiben Sie eine Notiz + {! note.dust !} <h2 class="note">{@message type="content" key="note.title"/}</h2> = // note_en-US.js var template = '<h2 class="note">Add a note</h2>'; We have a properties file that contains localized content by country. For the notes widget, somebody who speaks en in US will see the above. German in Germany will see the content underneath. The content is merged with the dust template, which generates a localized JS file by locale, that is loaded via require.js and rendered via dust.js. React can’t read .properties files, and we couldn’t change this, so we had to convert these to .json files.
  16. { // note_en-US.json note.title: Add a note", note.placeholder: You can

    enter a note here., // note_de-DE.json note.title: Notiz, note.placeholder: Bitte schreiben Sie eine Notiz } import React from 'react'; import { i18n } from 'react-i18n'; let Note = React.createClass({ mixins: [i18n('sendMoney/note')], render() { return ( <div className="note-wrapper"> <h2 class="note-title"> {this.i18n('note.title')} </h2> </div> ); } }); export default Note; We created a Grunt task to convert prop files to .json
  17. { // note_en-US.json note.title: Add a note", note.placeholder: You can

    enter a note here., // note_de-DE.json note.title: Notiz, note.placeholder: Bitte schreiben Sie eine Notiz } import React from 'react'; import { i18n } from 'react-i18n'; let Note = React.createClass({ mixins: [i18n('sendMoney/note')], render() { return ( <div className="note-wrapper"> <h2 class="note-title"> {this.i18n('note.title')} </h2> </div> ); } }); export default Note;
  18. import React from 'react'; import { i18n } from 'react-i18n';

    let Note = React.createClass({ mixins: [i18n('sendMoney/note')], render() { return ( <div className="note-wrapper"> <h2 class="note-title"> {this.i18n('note.title')} </ h2> </div> ); } }); export default Note; Next we created an i18n mixin based on react-intl.
  19. import React from 'react'; import { i18n } from 'react-i18n';

    let Note = React.createClass({ mixins: [i18n('sendMoney/note')], render() { return ( <div className="note-wrapper"> <h2 class="note-title"> {this.i18n('note.title')} </ h2> </div> ); } }); export default Note; Here you see how we require the mixin, we load it and specify the location of the content file, and then insert the content we want into the template. We have some magic that determines what country you’re in and which language you should see. Great. So now i18n works. At this point we only have one more issue.
  20. Require.js How many people here are on Require.js? Webpack? Something

    else? Who doesn’t us a module loader at all? There were 2 big issues with Require.js. 1) Client side dependencies for testing was hard with mocha 2) React is really built around the NPM ecosystem. If you want to experiment with Flux, Alt or Redux this is really painful to pull down and try out with Require.js. It’s really easy with…
  21. Webpack Jamund Ferguson, from my team moved us over to

    Webpack. He wrote a great post about this on the PP Engineering blog. You should go read it. The actual migration was about 2 days worth of work. He then issued a PR and it was open for a few weeks while we tested and reviewed it. We all loved it…
  22. Webpack • client-side require() npm modules • common.js • jsx

    • es6 The biggest thing was that we could now use client side npm require(). Everybody loved that. We could now use common js on the clientside. We could use Babel-loader which made it really easy to start using JSX and ES6. We were able to preserve all of our old amd code, w/o updating or changing, but also start using new great features like es6 and jsx. The new & old could live in harmony. That makes everybody happy because of cost of trying new things is low
  23. You might think: Do I have to do all these

    infra changes before I can move to react? (pause) The fact is, you should be doing these things anyway. At this point this is best best practices. This will improve your existing workflow. Let’s see an example: We can start using es6 modules now.
  24. define([ 'backbone', 'view/currencyCode', 'view/forms', 'view/InternationalMoney' ], function ( Backbone, CurrencyCodeView,

    Forms, IntlMoneyView) { return function populateCurrencyCodes (country) { var view = currencyCodeView;
  25. define([ 'backbone', 'view/currencyCode', 'view/forms', 'view/InternationalMoney' ], function ( Backbone, CurrencyCodeView,

    Forms, IntlMoneyView) { return function populateCurrencyCodes (country) { var view = currencyCodeView; We’re pulling in a currencyCode view file…
  26. define([ 'backbone', 'view/currencyCode', 'view/forms', 'view/InternationalMoney' ], function ( Backbone, CurrencyCodeView,

    Forms, IntlMoneyView) { return function populateCurrencyCodes (country) { var view = currencyCodeView; and assigning it to the CurrencyCodeView varible
  27. define([ 'backbone', 'view/currencyCode', 'view/forms', 'view/InternationalMoney' ], function ( Backbone, CurrencyCodeView,

    Forms, IntlMoneyView) { return function populateCurrencyCodes (country) { var view = currencyCodeView; which is now magically available in this inner function. Now let’s see the es6 version.
  28. import Backbone from 'backbone'; import CurrencyCodeView from 'view/currencyCode'; import Forms

    from 'view/forms'; import IntlMoneyView from 'view/InternationalMoney'; export default function populateCurrencyCodes (country) { var view = currencyCodeView; }; This is so simple. You can see which file is being loaded, and what variable its export is being assigned to. You can also see down below very easily what is being exported from this file. This is so clear. Import and export. It’s great.
  29. import Backbone from 'backbone'; import CurrencyCodeView from 'view/currencyCode'; import Forms

    from 'view/forms'; import IntlMoneyView from 'view/InternationalMoney'; export default function populateCurrencyCodes (country) { var view = currencyCodeView; Here’s the full example. Now, let’s talk about lessons we leared when we issued our…
  30. First Pull Request At this point the infrastructure was in

    place. Everybody was excited. But what should our strategy be moving forward?
  31. Rewriting our whole app at once is a non-starter. It’s

    just not feasible. It would be too time consuming and far too risky. It’s a 3 page flow but there’s a lot of edge cases that you have to consider. So we decided to move over one small feature. What feature? What’s a good candidate? Everything on this page is really important. Let’s keep moving.
  32. What’s the least important feature? This is a really important

    point. If we’re going to screw something up when we push this to prod, we want do screw up the note you send along with the transaction. We DO NOT want to screw up who you send money to. We also DO NOT want to screw up the amount. If you want to send your friend $100 but we charge you $1000 this is a VERY BAD situation.
  33. This note widget is also complex enough to be a

    great candidate. It has localized placeholder content. It has some JS functionality that resizes based on content. And there’s a character counter. So my wife went out of town for the weekend and I decided to moved over the note widget to React. I issued the first PR. Here’s what it contained:
  34. First React PR • Dust template -> react/jsx • decoupled

    resize logic from BB • wrote tests for resize code • added __tests__ folder next to the code • changed testing helpers to work with __tests__ This got merged instantly right?
  35. Sat open for two months What should I have done

    instead? The PR should have been much simpler.
  36. First React PR • Dust template -> react/jsx • decoupled

    resize logic from BB • wrote tests for resize code • added __tests__ folder next to the code • changed testing helpers to work with __tests__ All that really needed to change was the template and the event binding logic. But I got really excited and wanted to experiment. I created way too many decision points for my peers when they reviewed this PR. We needed to have a meeting to discuss all these new patterns. None of these things really mattered yet. So the lesson here is…
  37. Optimize for future change It’s only been 2 years since

    we chose our initial client side stack. 2 years is a short time to completely swap out your stack. So we have to ask ourselves ‘how can we reduce the cost of switching’? Around this time I found this great quote.
  38. – Michael Feathers “You have to build a barrier between

    yourself and the framework.” Michael Feathers wrote a great book called ‘Working Effectively with Legacy Code’. Most of deal with legacy code. What does this mean? If you only take one thing away from my talk, let it be this:
  39. – Jamis Charles “Use as much vanilla JS as possible.”

    By all means, still use React, React Router, Flux. All these are great and solve very specific problems. Beyond that really try to keep it framework agnostic. The problem we have right now is that everything is really tightly coupled. This prevents us from changing. Let’s take a look at an example from that notes widget.
  40. define(['jquery', 'backbone'], function ($, Backbone) { return Backbone.View.extend({ el: 'form',

    events: { 'keyup #note': 'resizeTextAreaField', 'blur #note': 'hideTextAreaCounters' }, // Resize text area as user types resizeTextAreaField: function (event) { var count = this.countTextContent(); var newHeight = this.getIdealTextAreaHeight(count); var newRows = this.getRowsFromHeight(newHeight); $('#note').height(newHeight).attr('rows', newRows); }, // Update textarea counter with remaining character left hideTextAreaCounters: function (event) { // pseudo code }, So what are the important pieces here?
  41. define(['jquery', 'backbone'], function ($, Backbone) { return Backbone.View.extend({ el: 'form',

    events: { 'keyup #note': 'resizeTextAreaField', 'blur #note': 'hideTextAreaCounters' }, // Resize text area as user types resizeTextAreaField: function (event) { var count = this.countTextContent(); var newHeight = this.getIdealTextAreaHeight(count); var newRows = this.getRowsFromHeight(newHeight); $('#note').height(newHeight).attr('rows', newRows); }, // Update textarea counter with remaining character left hideTextAreaCounters: function (event) { // pseudo code }, The event binding, and the business rules that control how the textarea grows when a user is typing in it. But what really needs to change when we move this from BB to React? 1) The event binding. 2) We have to decouple the business logic. Let’s see what that looks like
  42. define(['jquery', ‘backbone’, ‘utils/resizeTextareaUtil’], function ($, Backbone, ResizeUtil) { return Backbone.View.extend({

    el: 'form', events: { 'keyup #note': 'resizeTextAreaField', 'blur #note': 'hideTextAreaCounters' }, // Resize text area as user types resizeTextAreaField: ResizeUtil.resizeField, // Update textarea counter with remaining character left hideTextAreaCounters: ResizeUtil.hideTextArea, }; }); We now have moved our business logic into a vanilla file called resizeTextAreaUtil. We can easily require that into this file, and still bind this with BB events. We can also easily require that into a React component and bind that to some React event. This can now be used in future framework versions without having to change. Reality: If you don't build a barrier, your legacy React code in 2 years will be just as painful to migrate as your current legacy BB code is now. So you’ve made it easier to change. What’s left? How do you convince people?
  43. Reduce the cost of change If we reduce the cost

    of change, you'll get a lot less pushback. Less tightly coupled. Our Culture at PP is receptive to new stuff. If we want to move again in 2 years, I’m confident that we’ll do that. Next we’ll talk about things we did that worked.
  44. Worked • Conferences • Hack sessions over lunch • Distribute

    the work • Don’t alienate the last architect • Keep momentum Jamund did the infra. I did the React part. Have a very unifying effect. Excitement. Great to show off React, port things over, and address concerns. Watch videos. Work with him. Don’t say “this sucks we have to change”. Say “this piece is working, this other piece really isn’t working. Let’s fix that”.
  45. Solve real problems What pain points are you fixing? This

    is all really new and cool stuff. Story: At my last job at FamilySearch I wanted to drop jQuery. I’d read a bunch of articles and it sounded like a good idea. I was talking to the other engineers about it and they said: “PLEASE don’t make us learn something else. We’re overwhelmed enough with our current stack”. That brings me to my final thought.
  46. The principles that you learned here at React Rally are

    to help you solve real problems. If you don't have pain, don't make your team suffer. If you are facing problems, you can start applying these solutions we talked about today with or without react.
  47. Sources • Moving from Require to Webpack 
 https://www.paypal-engineering.com/ 2015/08/07/1450/

    • FE Masters React Course
 https://frontendmasters.com/courses/react/