MARCUS ÖSTERBERG

Stateless Function Components In React

JavaScript React Function Components

Stateless presentational components in React

With React your UI is built out of reusable components. It’s a modular way of development. In v0.14 Stateless Functions was introduced and lets you write Composable components. Components that are stateless and isolated. That means that we can write presentational components (basically components that returns good looking divs) that are pure functions. So no state, lifecycle methods or refs attribute.

Enough said! Lets see how these Stateless Function Components can be written and used.

Typical stateful component written with ES6 syntax.

class Parent extends React.Component {
  constructor(props) {
    super(props)
      this.state = {
        text: ''
      }
      this.addText = this.addText.bind(this)
  }
  
  addText(event) {
    this.setState({ text: event.target.value })
  }
    
  render(){
    return (
      <div>
      <h2>Parent: {this.state.text}</h2>
      <Text 
        addText={this.addText}
        text={this.state.text}
      />
      </div>
    )
  }
}


Parent passes down addText method and the state to our presentational component Text.

Lets create our stateless function component. If you are using the ES6 way of writing function expressions remember that the name property will not be set. Which can be a problem for debugging.

const Text = ({ addText, text }) => {
  return (
    <div>
      <h3>Child: {text}</h3>
      <input
        type="text"
        onChange={(event) => addText(event)}
      />
    </div>
  )
}


Text takes the properties as a parameter passed down from its parent Parent.
Could also pass the object props as a parameter

const Text = (props) => {
  return (
    <div>
      <h3>Child: {props.text}</h3>
      <input
        type="text"
        onChange={(event) => props.addText(event)}
      />
    </div>
  )
}



Notice how we dont have to use this keyword because its a function not an object.
You can still use Prop Validation on your function component

Text.propTypes = {
  addText: React.PropTypes.func,
  text: React.PropTypes.string
}

// And default props
Text.defaultProps = { text: 'default text' }


If your presentational component is small you can return your statement in one line

const Text = ({ addText }) => <input type="text" onChange={(event) => addText(event)} />



Stateless function components not only makes your code look cleaner, easier to test but also improves performance.
Check out the demo to see full example.

I hope you found this helpful, feel free to share your insights or comments below.

Enjoy your code.


comments powered by Disqus
Archive