1. What is the Component Lifecycle in React JS?
In React, Lifecycle of a component represents the different stages of the component during its existence.
The phases of a React Component Lifecycle are:
Phase | Description |
---|---|
Mounting | In the Mounting phase, the instance of a component is created and inserted into the DOM. |
Updating | In Updating phase, the component is updated whenever there is a change in the component's state. |
Unmounting | In Unmounting phase, the component instance is removed from the DOM. |
To know more about the Component life cycle, refer to Component Life Cycle | Cheat Sheet.
2. Explain about React JS Component lifecycle Phases?
- Kindly refer to Component Life Cycle | Cheat Sheet.
3. What are the Lifecycle methods of React?
Some of the React Component Lifecycle methods are:
componentDidMount: Executes after the first render. All the network call requests, DOM or state updates, event listeners are set up in this method.
shouldComponentUpdate: It is invoked before rendering when new props or state are being received. It returns
trueby default. If it returnsfalse, therendermethod will not be called.componentDidUpdate: It is invoked immediately after updating occurs. This method is not called for the initial render.
componentWillUnmount: It is invoked immediately before a component is unmounted and destroyed. All the cleanup activity is performed in this method. Examples: Canceling network requests, cleaning up any subscriptions, etc.
4. What is the method called between constructor() and render()?
- componentWillMount()will be called between constructor and render methods.
The
componentWillMount()had been marked for removal in React 16.3 and above versions.
5. When will we use the componentDidMount method?
The
Example: Setting timers, initiating API calls, etc.
In General we make API Calls inside
6. Write a React JS component, that updates the count whenever a button is clicked?
Maintain a state variable count. Update the count state variable in the onClick event handler.
We can update the state by using
setState(). Here, we have to provide function as an argument to update the state.
Example:
7. Write a React JS component that displays a Welcome message when I click a button?
8. What is an Event in React?
In React, Events are called Synthetic Events. These are not the same as the HTML DOM events.
Synthetic Events are the cross-browser wrappers around the HTML DOM events.
One of the advantages of Synthetic Events is:
As the same event has different names across different browsers, we need to write the different event names in different browsers accordingly.
But by these Synthetic Events, we can write only one event name in all Browsers. React takes care of the cross-browser issues.
Syntax:
- React events are named using camelCase, rather than lowercase.
- With JSX, you pass a function as the event handler rather than a string.
Example: