React Composition Patterns From The Ground Up

Written by alexkrolick | Published 2017/09/08
Tech Story Tags: javascript | jsx | composition | programming | react

TLDRvia the TL;DR App

This post explores the many ways React Components can be combined, mixed-in, and mixed-up, including:

  • The Lifting State & Container/Presenter Pattern
  • Higher-Order Components
  • Render Callbacks/”Function-as-Child”
  • “Renderless” State Providers

Building Blocks

First, a refresher on the essentials. We’ll start out without any JSX syntactical sugar so we’re clear what’s happening under the hood. Later we’ll explore JSX syntax and compositional techniques.

Elements

A React Element is a virtual representation of an HTML Element that is synced with the real DOM using the render function from react-dom. createElement is a utility to create React Elements.

Arguments to createElement:

  • type: DOM element name ("h1"), or handle to a function that creates elements (see Components below).
  • props: Properties to add to the DOM Element's attributes, or pass to the Component function.
  • ...props.children: any additional arguments are combined into an array called props.children. Nested arrays are flattened.

<a href="https://medium.com/media/fe4b5b6757949142c2b0f1dec4768bbe/href">https://medium.com/media/fe4b5b6757949142c2b0f1dec4768bbe/href</a>

Components

Components are functions that return renderable “nodes”: Elements, strings, null, or other Components. Components that extend the React.Component class are more abstract:

  • They must implement a render method that provides the return value as above
  • The component receives its initial prop arguments in the constructor and binds them as this.props; this.state can also be initialized at this point
  • render is called against a component instance so it has access to its props, state, and other properties
  • The component responds to changes in props by calling lifecycle methods such as componentWillReceiveProps (see Understanding React - Component Lifecycle)
  • If the component’s state or props change and all lifecycle hooks allow it, a re-render is scheduled and render is called again, returning a new virtual DOM tree
  • The virtual DOM returned by the component is compared against the actual DOM and any changes are synced to it. This is the crux of the React programming model, where the layout engine takes a declarative description of what the DOM should look like and “makes it so”.

<a href="https://medium.com/media/ad2edce6df8c4386c42a8756f83d42d1/href">https://medium.com/media/ad2edce6df8c4386c42a8756f83d42d1/href</a>

Unlike the static example in the Elements section, this HTML will update if Baz changes its state.

JSX

JSX is a syntax that transforms XML-like trees into createElement calls:

<a href="https://medium.com/media/e9720d0fb8c0c8f86d6fcac1945c2c3c/href">https://medium.com/media/e9720d0fb8c0c8f86d6fcac1945c2c3c/href</a>

Read JSX In Depth and WTF is JSX? for a deep dive into what you can and can’t do with JSX.

Composition Patterns

Lifting State & Container/Presenter

The simplest way to compose React components is to follow these rules:

  1. Divide components into stateful “containers” and stateless “presenters”.
  2. Pass functions (“callbacks”) that change the container state as props to children
  3. If two components need access to the same state, move the state into their common parent

<a href="https://medium.com/media/ccbe9e24d82741950385b9aef7a4bccb/href">https://medium.com/media/ccbe9e24d82741950385b9aef7a4bccb/href</a>

The React docs have a good explanation of how to structure components in this way: Lifting State Up

Higher-Order Component (HOC)

A higher-order component is a function that takes a component and returns a component. One use case is to inject additional props or context.

Think of an HOC as a component factory or a stage in a “component assembly line”.

<a href="https://medium.com/media/40d673cbad03f8fd76bba5a93b7915e2/href">https://medium.com/media/40d673cbad03f8fd76bba5a93b7915e2/href</a>

Without JSX it possible to use HOCs inline as well.

Examples

  • React-Redux uses an HOC called connect to map store state to props
  • React-Router’s withRouter HOC provides route context to components needing access to history APIs

Disadvantages

  • Creates a wrapper around components, allocating a new function and taking up space in the tree when debugging
  • Higher-order function composition doesn’t always work inline with JSX, depending on what you’re trying to do.

Render Callback/Function-as-Child

Since JSX children are turned into the 3rd argument to createElement, this argument can be repurposed to accept data types other than renderable nodes, such as a render callback (a function that returns a node).

<a href="https://medium.com/media/9ece982d46625674655a6b3b1835b49e/href">https://medium.com/media/9ece982d46625674655a6b3b1835b49e/href</a>

See Function as Child Component for an in-depth discussion of the approach.

Disadvantages

  • Implicitly redefining the meaning of the 3rd argument (children) in createElement seems hacky
  • Function signature is difficult to enforce (static checking works, using PropTypes at runtime is impossible)

“Renderless” State Provider

The “renderless” component pattern takes the container-presenter pattern to the extreme and forces state management to be implemented completely separately from render logic. A combine(Container, Presenter) utility function uses higher-order functions and inheritance to compose state containers with arbitrary stateless components.

The example below implements a StateContainer utility class and combinefunction:

<a href="https://medium.com/media/4588c99919bb73fc88e055e5c8da5cba/href">https://medium.com/media/4588c99919bb73fc88e055e5c8da5cba/href</a>

Discuss

Did I miss something? Discuss here:


Published by HackerNoon on 2017/09/08