React 16 - In theory, in practice & in the future

React 16 - In theory, in practice & in the future

C54966aee8a212367249f653d3b1f8d2?s=128

Giamir Buoncristiani

March 20, 2018
Tweet

Transcript

  1. REACT 16 in theory, in practice & in the future

  2. About me I am Giamir Buoncristiani. I am an Italian

    software engineer working at ThoughtWorks. I care passionately about UI development.
  3. Agenda In theory In practice In the future React 16

  4. Agenda In theory In practice In the future React 16

  5. What does it take to display a React application? Network

    Parse Compile Heap init Render Display I/O CPU
  6. How can we make the UX better? I/O CPU WHAT

    ABOUT DOING THE SAME AT THE FRAMEWORK LEVEL? CAN WE SPLIT REACT WORK INTO CHUNKS?
  7. React under the hood b div p span a i

    DATA Virtual DOM (JS) - $ React elements Real DOM - $$$ HTML elements
  8. React under the hood b div p span a i

    DATA Virtual DOM (JS) - $ React elements Real DOM - $$$ HTML elements b div p span a i
  9. React under the hood b div p span a i

    DATA Virtual DOM (JS) - $ React elements Real DOM - $$$ HTML elements b div p span a i b div p a i PROPS CHANGED span RECONCILER (REACT) NEW DATA span
  10. React under the hood b div p span a i

    DATA Virtual DOM (JS) - $ React elements Real DOM - $$$ HTML elements b div p a i b div p a i PROPS CHANGED span RECONCILER (REACT) NEW DATA span RENDERER (REACT-DOM) span
  11. The old reconciliation algorithm REACT STACK Recursion and the JS

    stack Browser main thread POTENTIAL LONG FRAME We cannot. How can we pause this process and resume later from where we left off? Can we split this work into chunks?
  12. The new reconciliation algorithm Gives control back to the main

    thread REACT FIBER Cooperative scheduling and requestIdleCallback Browser main thread React Fiber is a reimplementation of the React reconciler. It allows high priority updates to jump ahead low priority updates. It is built with full backward compatibility in mind Its new algorithm is a great foundation for async rendering features. It can pause visiting the tree at any time and restart later from where it left off.
  13. Agenda In theory In practice (new features) In the future

    React 16
  14. Reduced file size ~35% size decrease react (prod) react-dom (prod)

    react + react-dom (prod) 15.6.2 22.4KB (7.8KB) 127KB (38.9KB) 149.4KB (46.7KB) 16.2.0 6.5KB (2.8KB) 92.3KB (30.1KB) 98.8KB (32.9KB)
  15. New render return types Fragments Strings render() { return (

    <> Some text <h1>A heading</h1> More text </> ); } render() { return ‘Look ma, no spans!’; }
  16. Portals render() { // React does *not* create a new

    div. It renders the children into `domNode`. // `domNode` is any valid DOM node, regardless of its location in the DOM. return ReactDOM.createPortal( this.props.children, domNode, ); } Portals are a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. Please prefer using portals over using multiple react roots.
  17. Error Boundaries class ErrorBoundary extends React.Component { constructor(props) { super(props);

    this.state = { hasError: false }; } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } <MyApp> <ErrorBoundary> <WidgetA /> </ErrorBoundary> <ErrorBoundary> <WidgetB /> </ErrorBoundary> </MyApp> componentDidCatch(error, info) { this.setState({ hasError: true }); logErrorToMyService(error, info); }
  18. Improved server side rendering // Returns an HTML String ReactDOMServer.renderToString

    The server renderer has been completely rewritten // Returns a Readable stream that outputs an HTML string ReactDOMServer.renderToNodeStream
  19. Agenda In theory In practice (upgrade insights) In the future

    React 16
  20. JS environment requirements React 16 depends on the collection types

    Map & set // reactPolyfills.js import 'core-js/modules/es6.map'; import 'core-js/modules/es6.set'; // head.jsp <script type="text/javascript"> if(!("Map" in window && "Set" in window)) { document.write('<script src="/static/reactPolyfills.js?v=${version}"><\/script>'); } </script>
  21. Updating React 15 deprecated API React API breaking changes are

    minimal React codemod to update code which used the old api - import React, { PropTypes, Component } from 'react'; + import React, { Component } from 'react'; + import PropTypes from 'prop-types'; $ jscodeshift -t react-codemod/transforms/React-PropTypes-to-prop-types.js <path>
  22. Updating 3rd party libraries Package managers (npm, yarn, etc…) give

    you a warning for 3rd party libraries which have React 15 as a peer dependency. In our case these libraries worked fine after the upgrade to React 16. Anyhow we updated them to fix the package manager warnings. npm WARN mobx-react@3.3.1 requires a peer of react@^15 but none is installed.
  23. Updating tests Upgrade to Enzyme 3 is necessary // Configure

    Enzyme 3+ const Enzyme = require('enzyme'); const Adapter = require('enzyme-adapter-react-16'); Enzyme.configure({ adapter: new Adapter() }); In our case fixing unit tests was the area which took the most effort.
  24. Server side rendering performance Server side rendering time (mean) +47%

    SSR speed
  25. Server side rendering performance Node processes heap usage -34% SSR

    memory usage
  26. Agenda In theory In practice In the future React 16

  27. The new context API (16.3) A new version of context

    that provides a mechanism for a child component (Consumer) to access a value in an ancestor component (Provider). const MyContext = React.createContext( [defaultValue], [calculateChangedBits] ); const MyContextProvider = MyContext.Provider; const MyContextConsumer = MyContext.Consumer; <MyContextProvider value=“myContext”> // nestedComponents <MyContextConsumer> {value => ( <ComponentThatNeedsAccessToMyContext context={value} /> )} </MyContextConsumer> // nestedComponents </MyContextProvider>
  28. DEMO TIME

  29. Time Slicing (under construction) class TimeSlicing extends Component { state

    = { data: [], text: “” }; handleChange = ({ target }) => { } render() { return( <> <input value={text} onChange={this.handleChange} /> <Graph data={data} /> </> ); } } this.setState({ text: target.value }); this.deferSetState({ data: target.value.length });
  30. DEMO TIME

  31. Time Slicing (under construction) A generic way to ensure that

    high-priority updates like user input don’t get blocked by rendering low-priority updates. “Dan Abramov - React core team member”
  32. Suspense (under construction) class Wrapper extends Component { state =

    { data: null }; componentDidMount() { getData().then(data => { this.setState({ data }); }); } render() { return data ? <ComponentThatNeedsAsyncData data={data} /> : null } }
  33. Suspense (under construction) import { createFetcher } from ‘future’; const

    dataFetcher = createFetcher(getData); function Wrapper() { const data = dataFetcher.read(‘data’); return ( <ComponentThatNeedsAsyncData data={data} /> ); }
  34. DEMO TIME

  35. Suspense (under construction) “Dan Abramov - React core team member”

    A generic way for components to suspend rendering while they load asynchronous data.
  36. Takeaways React 16 already uses the new Fiber reconciliation algorithm

    but it still does not take fully advantage of it just yet. At the moment Fiber is used on compatibility mode with the old React stack reconciler and all updates are treated synchronously. Upgrading to React 16 seems to be pretty painless and it brings some performance benefits especially if you are doing SSR. A new stable version of the context API will be available in React 16.3. Time Slicing and Suspense are the two main async rendering features the React core team is working on. Hopefully they will be ready by the end of the year, but you can start playing with them today cloning my demos from Github.
  37. THANK YOU Giamir Buoncristiani https://giamir.com Github: giamir Twitter: @giamir Questions?