Best Practices of React Component
Consider below while designing react component
- Don’t update state (setState) in render method.
- Use constructor wisely. If you wish to bind event handlers or methods or initialize state then only use constructor.
- Do not assign props to state unless you wish to fix the value of state for that component.
- 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.
- Error boundaries must be used to recover from unexpected exceptions. Any component that defines any of the
static getDerivedStateFromError()
orcomponentDidCatch()
method becomes the error boundary. Error boundary catches error only from the components below them, it does not catches error within - 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).
- forceUpdate() triggers render() method and shouldComponentUpdate() method. This should be used carefully reckless use of it can lead to poor performance of your application.
- Use React.Fragment to avoid extra DOM nodes in your UI.
- Use componentDidMount() method to fetch api result, avoid using componentWillMount() as it will be deprecated in new version of react.
- Never include setState() in componentWillUnmount() as it will never be rendered and update will be missed
- 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.