Skip to content

Instantly share code, notes, and snippets.

@dabbott
Last active April 17, 2019 19:55
Show Gist options
  • Save dabbott/0492813d0939405b178016bc066e4d5c to your computer and use it in GitHub Desktop.
Save dabbott/0492813d0939405b178016bc066e4d5c to your computer and use it in GitHub Desktop.
Render function transformation

The main idea

The React way: let UI = ƒ(state)

Assume that our layers are predefined and return value of our render function needs to look like this:

let UI = {
  layers: {
    container: {
      backgroundColor: "..."
    },
    title: {
      text: "..."
    },
    subtitle: {
      text: "..."
    }
  }
}

We can treat this intermediate object value as a mutable object within our render function for simplicity.

layers.title.text = "Hello"
layers.title.text += ", Devin"

When we return UI, then we no longer make any changes to the object, and React can render it.

What the compiler does

The compiler gets rid of the intermediate object when generating code, instead doing the simplest set of assignments possible.

Imagine instead of the object, we have the following variables:

let layersContainerBackgroundColor
let layersTitleText
let layersSubtitleText

The compiler can determine which of these are actually needed, based on which keys are written multiple times. For example, if we have:

layers.container.title = parameters.greeting
if (...) {
  layers.container.title += ", " + parameters.name
}

Then we will probably want to use layersTitleText as an intermediate variable. If we don't assign to a variable more than once, we don't need an intermediate variable at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment