React with Router & Redux

Oct.17.2017 | 12m Read | ^UX

Facebook's React is an open-source framework (free, reusable code). It powers many complex User Interfaces (UIs) for apps. We shall cover not only the basic operations and lifecycle, but the MVC (Model View Controller) software pattern, networking protocols, and Redux (state management plugin). Get ready to read and React!

React:

A UI framework with JSX components (JavaScript plus 'X' or HTML and CSS compiling into a singular syntax). So buttons, images, text, and other elements are rendered and updated by state management. The states (objects) and props (values within the state object) are driven using a simplified virtual DOM (Data Object Model) tree.

This virtual DOM (ReactDOM) is smaller. That makes it a faster structure and data set to traverse before updating the web browser's actual DOM. NOTE: frameworkless code ('VanillasJS') or others with less overhead will still be faster (like SvelteJS and MithrilJS). React is designed to use the architectural pattern MVC (Model-View-Controller).

▼ Model-View-Controller:

    • ☑⁡⁡ Model: The data, typically located on servers and databases.
      ☑⁡⁡ View: The display or what you see on the screen.
        ⁡◆⁡⁡ Includes graphics, animation, and other components.
      ☑⁡⁡ Controller: The middleware between the view and the model.
        ⁡◆⁡⁡⁡⁡ Updates the view and model based on user and server interaction.
      ☑⁡⁡ Invented by Trygve Reenskaug ('Trig-va Reens-gaw') during the Objected-Oriented Programming craze in the 1970's.
        ⁡◆⁡⁡ ⁡⁡Originally developed and implemented in the 1980's for the SmallTalk language at Xerox PARC (Palo Alto Research Center).
        ⁡◆⁡⁡ ⁡⁡Apple and NeXT use MVC with WebObjects in Objective C and it is converted to Java. Later, Java's Spring UI framework adopts MVC. It is also used in Python's Django web framework and Rails (Ruby's web framework). Windows has its own ASP.NET MVC.
  • ▼ JSX alternatives:

    • ☑⁡⁡ React.createElement(): 'React.createElement(component, props, ...children)' is what JSX compiles into. It is unadvised to use this directly because the syntax is more verbose (wordy) and omission can break compatibility with some React packages (like bss ↗).
    • ☑⁡⁡ react-hyperscript ↗: less verbose syntax with easier inline styling for CSS than JSX. It is also less popular so you often must convert projects and learn both syntaxes. MithrilJS comes with its own implementation.

    React Component Lifecycle:

    ▼ render():

    • ☑⁡⁡ Tells the ReactDOM to allow the browser to draw the components onto the actual DOM layout.
        ⁡◆⁡⁡ NOTE: An internal React check is done first with componentDidMount().
      ☑⁡⁡ Typically returns a JSX element (component).
  • ▼ setState() :

    • ☑⁡⁡ Sets the state of the DOM component which stores its place in the ReactDOM lifecycle.
    • ☑⁡⁡ Has a callback function parameter (input) for further instruction upon completion (this is asynchronous or untimed and starts when ready).

    ▼ forceUpdate():

    • ☑⁡⁡ Skips over shouldComponentUpdate() to componentWillUpdate().
    • ☑⁡⁡ Discouraged unless you can not update properly.

    Stateful vs Stateless Components:

    ▼ Stateless (functional or presentational):

    • ☑⁡⁡ Has no state (object) and must be passed directly to the render function.
    • ☑⁡⁡ Simply returns props.
    • ☑⁡⁡ More difficult to clone since you have to write your own code to manage the props or copy them into a stateful component.
    • ☑⁡⁡ The ideal component for optimization.

    ▼ Stateful (class):

    • ☑⁡⁡ Has a state (object) to store and reference.
    • ☑⁡⁡ References to past, current, and future changes.

    ▼ 3 arguments passed to React.createElement():

    • ☑⁡⁡ [props]: properties array, usually enclosed in curly braces (like 'return { this.props.myProp }')}.
      ☑⁡⁡ type: element type, usually a JSX component.
      ☑⁡⁡ [...children]: children array passed to the created JSX component.
        ⁡◆⁡⁡ Stored under this.props.children.
  • React Router:

    ▼ What is routing?

    • ☑⁡⁡ Web page data is routed (directed) from file paths (local locations) to web addresses (URLs or Uniform Resource Locators).
    • ☑⁡⁡ These URLs are then usually attached to link UI components for page navigation.

    ▼ Client-side routing:

    • ☑⁡⁡ React Router and Reach Router (from a co-creator of React-Router) have client-side routing.
    • ☑⁡⁡ Requires more data storage and unpacking on the client.
    • ☑⁡⁡ Ideal for rendering or offloading server processing (faster deploy).
    • ☑⁡⁡ Reduced server load.
    • ☑⁡⁡ Ideal for high speed clients.
    • ☑⁡⁡ More responsive interfaces (no request bottleneck).
    • ☑⁡⁡ Better swappable or component-based architecture.

    ▼ Server-side routing:

    • ☑⁡⁡ GatsbyJS, NextJS, Reach Router (also routes client-side), React Static, and now React-Router 4+ (with StaticRouter).
    • ☑⁡⁡ Static Site Rendering (SSR): rendering JSX components (including routes) into static components (mostly HTML and CSS, making JavaScript optional).
    • ☑⁡⁡ Requires data requested from the server.
    • ☑⁡⁡ Ideal for pre-rendered data and feeding a dummy or terminal-like client.
    • ☑⁡⁡ Faster requests and page loads (less processing and data).

    ▼ <Route> component:

    • ☑⁡⁡ children: one child element, or multiple wrapped in a <div>.
    • ☑⁡⁡ exact: bool, true forces exact matches to location.pathname.

    ▼ <Route> props:

    • ☑⁡⁡ match: object with path URL matching data.
    /*************/
    /*   ES 6:   */
    /*************/
    
    let matchObject = { 
      key: 'myId',
      /* Parsed URL and path object: */
      params: {...}, 
      /* True if the entire path matches: */
      isExact: true, 
      path: '/myMatchingPath',
      url: 'myMatchingPieceOfURL'
    };
    • ☑⁡⁡ location: the to prop is either a string (URL) or an object.
    /*************/
    /*   ES 6:   */
    /*************/
    
    let locationObject = { 
      key: 'myId', 
      pathname: '/myURL', 
      search: '?mySearchQuery', 
      hash: '#myHash', 
      state: { 
        myState: true 
      } 
    };
    • ☑⁡⁡ history: various objects depending on the platform (and the history package). Below are rough examples of history objects in both ES5 and ES6 style syntaxes.
    /*************/
    /*   ES 6:   */
    /*************/
    
    let historyObject = {
      key: 'myId',
      /* Number of items in the stack: */
      length: '99',
      /* PUSH (add item), REPLACE, or POP (remove item): */
      action: 'REPLACE',
      hash: '#myHash',
      location: {
        key: 'myId',
        pathname: '/myURL',
        search: '?mySearchQuery',
        hash: '#myHash',
        state: {
         myState: true
       }, 
      },
      /* Functions: */
      push: (pathToPush, [state]) => {...},
      replace: (pathToReplace, [state]) => {...},
      /* Forwards the stack by number parameter: */
      go: (numberOfItemsForward) => {...},
      /* Like 'go(1);': */
      goForward: () => {...},
      /* Blocks navigation: */
      block: (prompt) => {...}
    };
    /*************/
    /*   ES 5:   */
    /*************/
    
    var historyObject = {
      key: 'myId',
      /* Number of items in the stack: */
      length: '99',
      /* PUSH (add item), REPLACE, or POP (remove item): */
      action: 'REPLACE',
      hash: '#myHash',
      location: {
        key: 'myId',
        pathname: '/myURL',
        search: '?mySearchQuery',
        hash: '#myHash',
        state: {
         myState: true
       },
      },
      /* Functions: */
      push: function (pathToPush, [state]) {...},
      replace: function (pathToReplace, [state]) {...},
      /* Forwards the stack by number parameter: */
      go: function (numberOfItemsForward) {...},
      /* Like 'go(1);': */
      goForward: function () {...},
      /* Blocks navigation: */
      block: function (prompt) {...}
    };

    ▼ <BrowserRouter> vs <HashRouter>:

    • ☑⁡⁡ <BrowserRouter>: routes React content made of pages.
    • ☑⁡⁡ <HashRouter>: routes hash-based anchors in your URL paths for static pages (like '#home' and '#contact').

    ▼ Override default component paths by:

    • ☑⁡⁡ Placing a backslash ('/') before:
      path = '/myPath';

    ▼ react-router vs react-router-dom vs react-router-native:

    • ☑⁡⁡ react-router: contains the core features and compatible components for export to react-router-dom (web browser React) or react-router-native (React Native for mobile apps).
    • ☑⁡⁡ react-router-dom: web DOM router features like the link component (handles web hyperlinks) and <BrowserRouter> (uses your browser's window.location.history). NOTE: not compatible with react-router-native.
    • ☑⁡⁡ react-router-native: mobile app native features NOTE: not compatible with react-router-dom).
    • ☑⁡⁡ When to use what?: use your platform's flavor of router (react-router-dom for web browsers or react-router-native for mobile apps). Sometimes when converting apps you may want to temporarily use react-router to save time.

    Redux:

    ▼ Flux model plug-in for APIs, databases, & servers:

    • ☑⁡⁡ Flux plugins replace React's default Model View Controller pattern with a one-way state flow (controller-views get from a store, pass to UI children for updates, but action creators put data into the store).
      ☑⁡⁡ Has a global store for state data management.
      ☑⁡⁡ Single Source of Truth:⁡ a state object tree known as store.
      ☑⁡⁡ Trades rigid overhead and performance for easily mutable states in large apps.
      ☑⁡⁡ React is for rendering and updating JSX ReactDOM components.
        ◆⁡⁡ Optional stateful components store their state in the rendering lifecycle.
      ☑⁡⁡ Other Flux plugins for React include MobX.
  • ▼ Actions (action-creators data):

    • ☑⁡⁡ Updates the store using data wrapped objects (sent by store.dispatch()).
        ⁡◆⁡⁡ NOTE: must have a type.
  • ▼ Reducers:

    • ☑⁡⁡ A function with the params (previousState, action) that returns or 'reduces' to the next state.

    Interfacing with APIs & Servers:

    ▼ HTTP vs TCP/IP, FTP, & UDP:

    • ☑⁡⁡ HTTP: Hyptertext Transfer Protocol.
        ⁡◆⁡⁡ Contains various web protocols accessed via an abstracted Application Layer.
        ⁡◆⁡⁡ Currently uses a single TCP connection on port 80.
        ⁡◆⁡⁡ UDP⁡ is available with plugins, but may have firewall issues due to blocked ports.
        ⁡◆⁡⁡ HTTPS (HTTP Secure) is a standardized extension (on port 443) that uses TLS or SLL security certificates and may be required for access.
      ☑⁡⁡ FTP: File Transfer Protocol.
        ⁡◆⁡⁡ Older than HTTP and not as good for small, multi-connections (like web pages).
        ⁡◆⁡⁡ Uses TCP on port 21.
        ⁡◆⁡⁡ Has various modes (like ASCII for text transfers that must be configured).
        ⁡◆⁡⁡ Weak security.
        ⁡◆⁡⁡ Wide browser support.
      ☑⁡⁡ TCP: Transmission Control Protocol.
        ⁡◆⁡⁡ Robust and slower protocol for secure and accurate data.
      ☑⁡⁡ IP: Internet Protocol.
        ⁡◆⁡⁡ Connectionless protocol from below TCP for addressing devices.
      ☑⁡⁡ UDP: User Datagram Protocol.
        ⁡◆⁡⁡ Fast and less robust or secure protocol for games and video streams.
      ☑⁡⁡ RTP/RTCP: Real-time Transport Protocol/RTP Control Protocol.
        ⁡◆⁡⁡ Uses UDP for video streams.
  • ▼ SOAP vs REST vs GraphQL:

    • ☑⁡⁡ SOAP: Simple Object Access Protocol client-server API.
        ⁡◆⁡⁡ Data formats: XML using HTTP, TCP, SMTP or UDP.
        ⁡◆⁡⁡ Higher security and reliability than REST at the cost of performance and more resources.
        ⁡◆⁡⁡ Older and standardized instead of flexible like REST.
      ☑⁡⁡ REST: REpresentational State Transfer client-server API.
        ⁡◆⁡⁡ Data formats: JSON, HTML, XML, YAML, and text using only HTTP or HTTPS.
        ⁡◆⁡⁡ Scalable, browser friendly, and caching with flexible architecture.
      ☑⁡⁡ GraphQL: Graph Query Language API (open-sourced by Facebook in 2015).
        ⁡◆⁡⁡ Data formats: JSON, HTML, XML, YAML, and text using only HTTP or HTTPS.
        ⁡◆⁡⁡ REST replacement with start and endpoints for querying or injecting data in a single request. This creates less overhead and processing (like parsing or extracting useful parts).
        ⁡◆⁡⁡ Add-ons: GraphQL needs to access data (like the SQL database PostgreSQL ↗). These data requests must be translated for use (like from the SQL language). Here are some add-ons to make this much easier Hasura ↗ (a serverless GraphQL compiler), Prisma ↗ (an ORM or Object Relational Mapping proxy server), and Apollo ↗ (a client-server system).
  • ▼ Actual CRUD functions:

    • ☑⁡⁡ Create Read Update Delete: basic function layout for a client-server app.
      ☑⁡⁡ GET(): read server data and locally store it.
      ☑⁡⁡ HEAD(): read server data and locally store it, but only from the HEAD or header.
        ⁡◆⁡⁡ Header data is much smaller and comprised of notes about the BODY data (like sender's IP address and protocol).
      ☑⁡⁡ PUT(): write server data to a URI (URL or URN).
      ☑⁡⁡ DELETE(): remove (or deactivate) server data.

  •        : NEWS