Explain lifecycle of ReactJS due to all call to this.setState() function
React is a UI library. It renders components written in JSX. You can build and render any components as per your usage. React.js introduces the concept of state. The states are used to store data for specific components. These states can be updated accordingly using this.setState function. Updating of state leads to the rendering of UI. Different lifecycle methods are called during these renderings.
Lifecycle methods called when app is loaded first:
Lifecycle methods called when this.setState is called:
Approach: Let us create a React project and then we will create a UI that sends a call to this.setState. Users can interact with the UI and click on the button to trigger an event to call this.setState through this. Users can view all the lifecycle methods mentioned above in the console view.
Creating React Project:
Step 1: To create a react app you need to install react modules through npx command. “npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once.
npx create-react-app project_name
Step 2: After creating your react project move into the folder to perform different operations.
Project Structure: After running the commands mentioned in the above steps, if you open the project in an editor you can see a similar project structure as shown below. The new component’s user makes or the code changes we will be performing will be done in the source folder.
Example: We will create a button that sends a call to update the state through this.setState.
Step to run the application: Open the terminal and type the following command.
Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the console. Appropriate functions are called when the state is updated.