Middle
Tell about rendering and the lifecycle of components in React.
sobes.tech AI
Answer from AI
In React, the component lifecycle describes the sequence of stages from creation to removal of a component.
Main lifecycle stages:
-
Mounting: the component is created and inserted into the DOM.
constructor— initializes state.render— returns JSX.componentDidMount— called after insertion into the DOM, suitable for API requests.
-
Updating: occurs when props or state change.
shouldComponentUpdate— decides whether to re-render the component.render— updates the UI.componentDidUpdate— called after updating.
-
Unmounting: the component is removed from the DOM.
componentWillUnmount— resource cleanup, cancel timers.
In functional components with hooks, the lifecycle is managed using useEffect, which can mimic mounting, updating, and unmounting behaviors.
Example with a hook:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
// componentDidMount and componentDidUpdate
document.title = `You clicked ${count} times`;
return () => {
// componentWillUnmount
console.log('Cleanup');
};
}, [count]); // effect runs when count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}