Best Practices of React Component

April 29, 2019 Off By admin_manish

Consider below while designing react component

  1. Don’t update state (setState) in render method.
  2. Use constructor wisely. If you wish to bind event handlers or methods or initialize state then only use constructor.
  3. Do not assign props to state unless you wish to fix the value of state for that component.
  4. Plan meticulously if you are using shouldComponentUpdate(), try to use built in pure component instead. Correct usage of this lifecycle hook can improve the performance greatly.
  5. Error boundaries must be used to recover from unexpected exceptions. Any component that defines any of the static getDerivedStateFromError() or componentDidCatch()method becomes the error boundary. Error boundary catches error only from the components below them, it does not catches error within
  6. setState() enqueues changes of the state. It is not a good decision to use this.state immediately after setState() has fired. Use a callback provided by setState(update, callback).
  7. forceUpdate() triggers render() method and shouldComponentUpdate() method. This should be used carefully reckless use of it can lead to poor performance of your application.
  8. Use React.Fragment to avoid extra DOM nodes in your UI.
  9. Use componentDidMount() method to fetch api result, avoid using componentWillMount() as it will be deprecated in new version of react.
  10. Never include setState() in componentWillUnmount() as it will never be rendered and update will be missed
  11. Unsubscribe any subscription used in the component in componentWillUnmount()

For better control of your components use lifecycle hooks carefully. Careful use of lifecycle hooks can greatly lighten your component’s code burden.