There are various advantages of using React lifecycle methods in building SharePoint Framework components. It is not a necessity to use component lifecycle methods but we could get a lot out by using these methods with states. For a generic understanding of React component lifecycle methods, check here
Few of the benefits of using React component lifecycle methods are :
1. Distribute any data pull workloads between initial load and component updates cycle. Not all data need to be loaded during the render method call. We could break the component load into various cycles.
2. Identify changes and implement code based on property or state changes.
3. Isolate any component load issues into various stages
React Component Lifecycle methods:
1. OnInit method – This is the start method of the web part. It is suggested not to do much here, unless it is required by the webpart life cycle.
Use Case: Mostly this method could be used initiate environment level variables or global variables such as spcontext of PnPjs library.
2. ComponentWillMount – This method is called before the render method every time the control is loaded or refreshed.
Use cases: The code related to initial data pull for controls could be placed in this method. This is where the data feeds into required for dependency driven controls for eg. Web service and REST calls. It is advisable to show a loading message during this function run.
3. ComponentDidMount – This method is called after the render method every time the control is loaded or refreshed. The code related to pre-population of controls could be placed here.
Use cases: This method is mostly used to load the state of the controls. Since React code is a state driven Framework, any state changes updates the controls with new changes but doing it here allows to set default values if needed before the state is updated for long running business rules.
4. ComponentDidUpdate – This method is called every time a Property or State is updated. Based on the update and if anything has changed, the implementation code could be run.
Use cases: In this method, we could check if a property or state has changed and act on the change.
With regards to state, it is beneficial when you would like to only make further REST calls or complex business logic when key fields are updated.
With regards to property changes it is beneficial when you would like to reload the state of the component based on this change.
Note: There are other life cycle methods in React which do the same but they might be deprecating soon.
5. Render method : This method is called to render the final HTML based on state change. We can include some switch logic or call html rendering functions.
Use cases: The use case is pretty simple for this one, reneder all the HTML on to the page.
In this blog, we have looked at some of the use cases of using life cycle methods of React components to distribute the web part functionality across various life cycle methods.