React Component Pattern

Topics

  1. Class component

  2. Functional component

  3. Hi-order component

  4. Render callback component


Class Component

Class Component has state, life cycle methods. More importantly, class component can have shouldComponentUpdate method which allows us to set if the component should update or not.

class ViewDashbaord extends React.Component { 
  render() {
    return <div>Dashboard</div>
  }
}

Functional Component

Functional Component should used for component not requires state, re-render, life cycle methods.

const Button = ({ onClick }) => {
  return <button onClick={onClick}>Submit</button>
}

Smart Container

Smart container is component which connects to redux state and listens state changes. Listening state causes re-rendering so developers should be aware of making containers.

@connect(mapStateToProps, mapDispatchToProps)
class UserLists extends React.Component {
  render() {
    return <div>{this.users.map(user => <div>{user.name}</div>)}</div>
  }
}

Hi-order component

It is same concept as hi-oder function in functional programming paradigm. It wraps components and adds common methods to it.

const withSendEventData = (Component) => {
  return class withSendEventData extends React.Component {
    constructor() {
      this.handleSendUserEvent = this.handleSendUserEvent.bind(this)
    }

    handleSendUserEvent() {
      const { action, eventName } = this.props
      $.ajax({
        url: `https://tracking.sample.com?action=${action}&eventName=${eventName}`
      })
    }

    render() {
      const enhanceProps = {
        handleSendUserEvent
      }
      return <Component {...this.props} {...enhanceProps} />
    }
  }
}

https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e

Render callback component

Render callback component allows us to pass a function includes component. It can be container and pass different UI.

class CurrentTime extends Component {
  render() {
    const { children: renderFn } = this.props
    return (
      renderFn({ time: this.state.time })
    )
  }
}

class Dashboard extends Component {
  render() {
    return (
      <CurrentTime>
        {((time) => (
          <div>
            <span> Time is { time } </span>
          </div>
        )}
      </CurrentTime>
    )
  }
}

https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f

results matching ""

    No results matching ""