Skip to content

Instantly share code, notes, and snippets.

@TyrealGray
Last active November 12, 2018 17:18
Show Gist options
  • Save TyrealGray/9c78a67383dd36711077ddeb4cc4608a to your computer and use it in GitHub Desktop.
Save TyrealGray/9c78a67383dd36711077ddeb4cc4608a to your computer and use it in GitHub Desktop.
Lifecycle in React Native Component

Lifecycle in React Native Component

When we are developing our app, there are some features we always need to add, e.g. ListView components only refresh when the data in listItem is changed, initializing data before render function but not in the constructor function…

React Native component has already been implemented with many native optimization for us, but those features above are not. To do that, we need to override lifecycle function in React Native component.

The Component Lifecycle API

First of all, this is the official site docs about the API we could use:https://facebook.github.io/react/docs/react-component.html#the-component-lifecycle

The order of lifecycle should be: constructor() -> componentWillMount() -> render() -> componentDidMount() -> [ runtime loop ] -> componentWillUnmount()

The runtime loop has two possible situations: [ new props coming update ] -> componentWillReceiveProps() -> shouldComponentUpdate() -> componentWillUpdate() -> render() -> componentDidUpdate() -> [ runtime loop ]

[ new state coming update ] -> shouldComponentUpdate() -> componentWillUpdate() -> render() -> componentDidUpdate() -> [ runtime loop ]

So the new props data will trigger the componentWillReceiveProps() function but new state data will not.

For example,in our app we could use shouldComponentUpdate(nextProps, nextState) function to decide Listview component should re-render listItem or not.

shouldComponentUpdate(nextProps, nextState) {
  let changed;
  const detailsChanged = nextProps.details !== this.props.details;
  const dataChanged = nextProps.data !== this.props.data;
  changed = detailsChanged + dataChanged;
  return changed > 0;
}

Can we use setState() function in Lifecycle?

Yes, but only a few. You can use setState() in componentWill(Did)Mount() and componentWillReceiveProps() functions. Never do it in other runtime loop function, it will cause endless looping.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment