about code ¯\_(ツ)_/¯

Common Frontend Concepts

React and the rest of the frontend development world is full of new terms. Anyone new can quickly feel overwhealmed. I’m going to try and explain the most popular terms that you will come across when working with React. Think of this as a glossary of things you will come across.

Web Platform

This is the browser. Modern browsers are full of features and APIs that let you build whatever you want. They contain APIs for databases, video / audio streaming, 3D rendering, notifications, cryptography and tons more. At the heart of the modern browser is the DOM, HTML / CSS rendering engines and the Javascript core using these APIs is using the platform.

DOM

It stands for Document Object Model. And in short it’s all the HTML on the page. Usually there is a parent element like HTML, BODY, etc than child elements like DIV, SPAN, INPUT, etc. Also since a parent can have multiple children there are siblings too. Elements hve attributes such as class, id, style, etc that are either used to change the look and feel of the element or target the element for some other modification. id attributes are usually unique in the DOM while classes can be reused.

<HTML>
  <BODY>
    <DIV id='content'>
    <H1 class='title'>Hello World</H1>
    </DIV>
  </BODY>
</HTML>

Single-page Application (SPA)

Traditionally a website was a bunch of HTML pages with links. When you click on a link a new web page is fetched from the server and shown to you. Nothing wrong with this it still works great.

But what if you wanted your website (aka. Web App) to feel more snappy and behave more like a desktop or mobile app. Say you wanted it to work even without an internet connection and you wanted page switching to be instant.

To achieve this you need a React app that would take controlled of some of the natural behaviour of the web brower and change it to your likeing. Clicking on links in your app would not fetch a new page from the server but instead would change the components displayed in your react app. Also when data is required and a connection to the internet is not available your app would fetch old data from a local cache (tempeory store). Your app would now be called a Single-page app (SPA)

In short SPAs look and feel less like a website and more like a traditional desktop or mobile app.

ES5, ES6 etc

Another name for Javascript is ECMAScript Language Specification standard but we’ll just called it JS for short.

That aside this ECMAScript or ES for short is being worked on and improved. These improvements to the language are bundled together and under a name like ES5, ES6, ES2015, ES2016.

When writing React code you’ll be using newer versions like ES6, ES7, etc. These new versions have lots of cool features like Arrow notations and Spread Operator. Don’t worry about what those means just assume they are useful to us.

The problem is that not all web browsers don’t support ES6, ES7, etc. This is why we depend on our trustly old Webpack (Which itself uses something called Babble) to turn our code into ES5 code which all browsers understand.

Bundlers

Your React Web App will contain many Javascript and CSS files. A bundler such as Webpack will take all of these files and process them and combine them into a single bundle file. It could be more than one based on the rules you defined to split these into multiple bundles.

This way when your Web App is fetched by the browser it only has to get a single bundle (or few bundles) speeding up the fetch.

Package Managers

There are two very famous ones. You’ve probably heard of them, NPM and Yarn. I recommend Yarn. They are responsible for downloading the correct version of a library that your app depends on. For example a package manager would be responsible for downloading the React library that you would quite obviously need.

The libraries you depend on and their versions are defined in the package.json file. Your downloaded libraries are kept in a folder called node_modules and a file called yarn.lock (or npm.lock) is created to list everything that was downloaded and it’s exact version.

JSX

It is a special syntax (template language) used within your React component to write HTML code. Your React component is a mixure of Javascript, JSX and CSS code.

Below is a small react component, the line starting with const is a Javascript arrow function and within it is JSX code <h1>Hello, {name}</h1>

const HelloWorld = ({ name }) => (
  <h1>Hello, {name}</h1>
)

Components Lifecycle

A component lives it’s entire life in your app. It comes to life when its render() function is run and the rendered HTML is added to the DOM. This is called mounting and when this happens a function called componentDidMount() is called.

When some prop (data) given to the component from it’s parent changes the shouldComponentUpdate() function is called and based on if that returns true or false the render() function is called once again.

Finally when the component is removed for whatever reason the componentWillUnmount() function is called after its HTML is removed from the DOM.

To keep this explaination simple I’ve skiped several other functions that are also called on the component read the docs for those.

React components vs Web components

Yes, these are two seperate things. Web components” are created using something called the Custom Elements API that newer browsers support. In short they are not created using a framework and are very close to the browser.

React components on the other hand don’t use this browser API they are created using Javascript and the React framework. There are many advantages to using React components. I recommend going with React components, they will help you get your job done quicker and are also the popular and more mature option.

Rollup

Rollup is a bundler similar to Webpack. While Webpack does a everything and anything including dealing with all types of files, Rollup is focused only on Javascript. Rollup is designed to build distributables JS libraries. It’s so good at this one job that Facebook uses it to build React itself.

Why should you care about Rollup, mostly cause it creates smaller and faster bundles. Rollup creates ES2015 modules, which are better than CommonJS modules, which are what Webpack creates. This makes it easier for Rollup to remove unused code using something called Tree Shaking.

Use webpack for apps, and Rollup for libraries

― Da Internets

Server Side Rendering (SSR)

React was created to make sites more dynamic. React is a Javascript framework so until the JS code for your app is not downloaded and run you site will not render. Also what if you want your site to be picked up and indexed by Google. Most of us don’t really know how Google deals with websites that are entirely in Javascript.

This is where server-side rendering can help. In short its the act of running your React code on the server and only sending back the resultant HTML. Yes the final can still be dynamic the only difference is that it can be faster and more SEO friendly.

React Hot Reload

Hot reload is when you can make code changes and have your app render with the new changes without loosing state information. Lets assume you are building an app which requires the user to go though multiple screen. Normally any code changes would cause all state to be thrown away and the user would go back to the first stage. The problem with this is that it slows down your development cycle as you again have to go though all the work to get to the view your working on. What if you could continue to develop your app, see the changes in the view but not loose your state.

Next.js / Gatsby

Next.js and Gatsby are two seperate open source projects that aim to make it easy to publish React applications to the world. They each do this in a slightly different way.

One thing that these projects share in common is that they take care of all the complixity around bundling, packaging, Webpack, etc. And they provide you a simple command line tool to help you quickly get started with building and publishing your app.

Another thing they both do in common is server-side rendering so your React app is run on the server and only the resultant HTML is sent to back to the browser. The difference here is that Next.js does that in realtime as in when thhe browser requests your app and Gatsby does this when your build your app.

In short Gatsby is focused on helping your create static sites in React while Next.js focues on more dynamic sites. Yes, you can create dynamic sites in Gatsby too but it’s a little more work.

GraphQL

When your React app needs to fetch data from a server you have a few choices. The most popular choice right now is called REST APIs. It’s when you have an HTTP endpoint for every data type your application uses. For example to fetch all users https://yourdomain.com/api/users or to fetch a single user by his id .../api/users/123

Usually these APIs are pretty inflexible if you need more or less data then you would have to create a whole new API or make changes to the backend code. The problem some people have with this is that is requires constant changes to the backend code and limits the flexibily of the frontend (React) developer.

GraphQL is widely considered the solution to this problem. GraphQL is a web query language similar. A GraphQL query is way to ask for specific information and get exactly that. A frontend developer has full control of this query and therefore can ask for exactly what he needs and does not have to depend on anyone else.

Your data needs to be described to GraphQL. In this case the user has a fullname, title and list of followers.

type User {
  fullname: String
  title: String
  followers: [User]
}

A GraphQL query asking for the fullname of the user with the id 123

{
  users(id: 123) {
    fullname
  }
}

The result is exactly what was asked for just the users fullname

{
  "user": {
    "fullname": "Martin Bryce"
  }
}

Polyfill

Browsers are constantly getting new functionality and often there is a timeframe when some browsers support something before others. Polyfill is the name given to using javascript to fill in that missing funtionality on those other browsers.

For example let’s pretent the sessionStorage and localStorage api is unable on some browsers and you intend to use it in your app. In this case you will use a polyfill to ensure that your app works across browsers.

The polyfill in this case would use say cookies along with some Javascript code to recreate this api on browsers where it does not yet exist. It’s clearly not the same thing but it’s good enough to ensure your app works.

if (typeof window.localStorage == 'undefined') {
  window.localStorage = function() { .... }
}

if (typeof window.sessionStorage == 'undefined') {
  window.sessionStorage = function() { .... }
}

Redux / Flux

Flux is not a library or a software package, it’s an architure. It was promoted as a way to handle data flows within a React app. Everything in Flux revolves around the concept of a store. This is a blackbox that is support to hold all the data for the app. Data from the store is passed down to the React components of the app though their props. If an action like clicking a button needs to modify the data in a store it does that though dispatchers which contain the knowledge needed to modify this data. Displatchers are called though actions.

Redux is a popular library that implements the Flux architure. Redux adds a ton of extra boilerplate to code to your app so be sure you need it before reaching for it.

Dan Abramov, the creator of Redux has a great written article You Might Not Need Redux to help you understand if you need it.

Flow

Javascript is dynamic language with no type checking. In short if you have a function which takes a number and you pass it a string it will not warn you.

Types provide you some level of safetly especially if you are changing a lot of code. A type checker will ensure you don’t make mistakes.

Flow is the answer to this problem, it is a static type checked for Javascript. Flow was created by Facebook and is pretty feature rich. The code below will be flagged as an error by Flow since you are passing a string value "2" to a function which obviously only accepts numbers. I recommend you use Flow if possible.

// @flow
function square(n) {
  return n * n; // Error!
}

square("2");

React Native (Mobile and Web)

React Native is a framework created by Facebook that helps you build native iOS and Android apps using React. When I say native apps I don’t mean HTML apps running inside browser views. These are real mobile apps, just like if you were to build them in Java, Swift or Obj-C.

As you can see below a React Native component is very similar to the traditional React component that you know about. And having worked on builing native mobile apps for various platforms I think this is just pure magic.

There are obviously something that are different. If you look at the example you’ll see we don’t use HTML tags instead we have this <View> and <Text> tags. Since you are not building HTML apps you cannot use HTML and CSS like you do on the web here you have to use the components that React Native provides. React Native does have StyleSheet which is their own version of CSS to help style native components.

import React, { Component } from 'react';
import { Text, Stylesheet, View } from 'react-native';

class WhyReactNativeIsSoGreat extends Component {
  render() {
    return (
      <View style={styles.box}>
        <Text style={styles.text}>
          If you like React on the web, you'll like React Native.
        </Text>
        <Text style={styles.text}>
          You just use native components like 'View' and 'Text',
          instead of web components like 'div' and 'span'.
        </Text>
      </View>
    );
  }

  const styles = StyleSheet.create({
    box: { padding: 10 },
    text: { fontWeight: 'bold' }
  });
}

React Native Web is taking this magic further. React Native apps by themselves are native mobile only, you cannot use them on the web. This means you have two seperate code bases. React Native Web wants to change that so a single app codebase can be used on the web and on mobile.

Best of all this is already out there and can be used today. A great example of a successful React Native app in production is the Twitter mobile website

Typescript

Typescript is a web programming language created by Microsoft. It’s similar to Javscript in certain ways but does a lot more. The main reason people pick this over plain Javascript is type checking that’s built into the language. We could achieve similar results using plain old Javascript with Facebook Flow.

The other reason people pick Typescript is the language itself which in their opinion is better to work in than Javascript.

Here’s an example of a React component built with Typescript. You’ll notice both the props like name and age have their types defined. Additionally age? means age is an optional prop.

// src/components/Hello.tsx

import * as React from 'react';

export interface Props {
  name: string;
  age?: number;
}

function Hello({ name, age = 18 }: Props) {
  if (age <= 0) {
    throw new Error('You\'re clearly not that young :D');
  }

  return (
    <div className="greeting">
      Hello, I'm { isAdult(age) ? 'an adult' : 'a kid' }
    </div>
  );
}

export default Hello;

// helpers

function isAdult(age: number) {
  return age > 18;
}

ReasonML

This is a new language in the web programming world. Essentially it’s an old programming language called Ocaml with a new syntax. The new syntax is designed to help make it easier for Javascript programmers to move to ReasonML.

People tend to choose ReasonML because it is a purely funtional language with strong type checking. Additionally it’s quite easy to interact with excisting Javascript code which makes it easy to slowly start introducing ReasonML into your existing Javascript application. ReasonML compiles down to Javascript code.

Here’s an example of a React component in ReasonML. Personally I’m quite excited about ReasonML and woul love to see it become my goto web programming language in the future.

let component = ReasonReact.statelessComponent("Greeting");

let make = (~name, _children) => {
  ...component,
  render: _self =>
    <button>
      {ReasonReact.string("Hello!")}
    </button>
};

Follow me at twitter.com/dosco

  • Getting started with React

    Getting started with anything new is hard. In the frontend development world things are always changing, and changing fast. We’re gonna cut though all the complexity and get you Ninja status asap.

  • Data and React components

    The post second in this series on React. We focus on how data flows in and out of a React component and how you can use this data to connect multiple components together to build an app.

  • Building larger apps in React

    Having multiple pages in an app is pretty common. Take for example the Amazon app which has products and when you click one you get a detailed look at it. You’re gonna need to know how to build a React app with multiple pages so follow along.

  • Fetching Data in React

    Every React app needs to work with remote data. In this article we’ll walk though how you can make your React components talk to APIs and work with data.

  • Common Frontend Concepts

    React and the rest of the frontend development world is full of new terms. Anyone new can quickly feel overwhealmed. I’m going to try and explain the most popular terms that you will come across when working with React. Think of this as a glossary of things you will come across.