Middle
Tell about the lifecycle of a React component: main stages mount, render, unmount.
sobes.tech AI
Answer from AI
The React component lifecycle includes several key stages:
-
Mounting — creating the component and inserting it into the DOM.
- In class components, the constructor is called, then
render(), followed bycomponentDidMount(). - In functional components with hooks — the component function is called first, then the
useEffecthook with an empty dependency array.
- In class components, the constructor is called, then
-
Rendering — the process of generating the virtual DOM based on the current state and props.
- The
render()method is called in class components. - In functional components — the component function is invoked.
- Rendering can occur when state (
setState) or props change.
- The
-
Updating — occurs when state or props change.
- In class components,
shouldComponentUpdate()andcomponentDidUpdate()methods are called. - In functional components — the component function and hooks are called again.
- In class components,
-
Unmounting — removing the component from the DOM.
- In class components,
componentWillUnmount()is called to clean up resources. - In functional components — cleanup function in
useEffect.
- In class components,
Example with a functional component and hooks:
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// componentDidMount
console.log('Mounted');
return () => {
// componentWillUnmount
console.log('Unmounted');
};
}, []);
return <div>Hello, React!</div>;
}
Thus, the lifecycle manages the creation, updating, and removal of the component, enabling side effects and optimizing application performance.