Functional UI

So Hot Right Now

by Will Klein 

(Pure) Functions

+

UI Components

Teachers

Pure Functions

Pure Function

  • Given the same input, will always return the same output
  • ...
  • ...

Pure Function

  • Given the same input, will always return the same output
  • Produces no side effects
  • Relies on no external 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" }

A Brief History

of Frontend

Postback Model 

jQuery Era 

Client-side Templating

Single-page Apps 

Component-oriented Architecture 

Tree of Components

  • FilterableProductTable
    • SearchBar
    • ProductTable
      • ProductCategoryRow
      • ProductRow

Encapsulate!

  • Fetching data
  • Managing state
  • Rendering UI

Encapsulate!?

  • Too many concerns
  • Hard to test
  • Hard to reuse

Smart vs Dumb Components 

Smart

  • Example: App
  • Stateful Containers
  • Very little or no UI

Dumb

  • Example: Text
  • Stateless presentational
  • Renders UI

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

So Hot Right Now

Thanks!

Twitter @willslab

Slack @willklein on Denver-Devs

 

Made with Slides.com