Functional UI

Pure Functions

+

UI Components

by Will Klein 

Pure Functions

Pure Function

  • Given the same input, will always return the same output
  • Produces no side effects
  • Relies on no external mutable state

Pure Function

function hello(name) {
  return `Hello ${name}!`
}

> hello('Amelia')
"Hello Amelia!"

Impure Function

var name = 'Amelia'

function hello() {
  return `Hello ${name}!`
}

Impure Function

> hello()
"Hello Amelia!"
> name = 'Diane'
> hello()
"Hello Diane!"

Impure Function

var person = {}

function hello(name) {
  person.name = name
  return `Hello ${name}!`
}

Impure Function

> person
{}
> hello('Amelia')
"Hello Amelia!"
> person
{ name: "Amelia" }

History of UI

Postback Model 

jQuery Era 

Client-side Templating

Single-page Apps 

Component-oriented Architecture 

Tree of Components

  • FilterableProductTable
    • SearchBar
    • ProductTable
      • ProductCategoryRow
      • ProductRow

Encapsulated (heavy) Components 

Encapsulated but Heavy

  • Fetching data
  • Managing state
  • Rendering UI

Smart vs Dumb Components 

Smart Components, AKA

  • Container
  • Controller
  • Stateful

Dumb Components, AKA

  • Presentational
  • Stateless
  • Pure

Stateful

  • Example: App
  • Children are stateful or pure components

Pure

  • Example: Text
  • Children are pure components

React Components

export class Hello extends React.Component {
  constructor(props) {
    super(props)

    state = {}
  }

  render() {
    return (
      <p>Hello { this.props.name }!</p>
    )
  }
}

React Class

const element = <Hello name="Amelia" />

ReactDOM.render(
  element,
  document.getElementById('root')
)

React Class

function Hello(props) {
  return (
    <p>Hello { props.name }!</p>
  )
}

React Function

Functional Benefits

Separation of

  • stateful app components/code
  • stateless, pure UI components
function Hello(props) {
  return (<p>Hello { props.name }!</p>)
}

describe('Hello', () => {
  it('should say hi', () => {
    const wrapper = shallow(<Hello name="Amelia" />)

    expect(wrapper.html())
           .toEqual('<p>Hello Amelia!</p>')
  })
})

Testable

function Hello(props) {
  return (
    <p>{ props.name }</p>
  )
}

function App() {
  return (
    <div>
      <Hello name="Amelia" />
      <Hello name="Diane" />
    </div>
  )
}

Composition

Functional UI

Thanks!

Twitter @willslab

Slack @willklein on Denver-Devs

ReactJSDenver.com

Functional UI Components

By Will Klein

Functional UI Components

HTML5 Denver - Mon Mar 20, 2017

  • 303
Loading comments...

More from Will Klein