Middle+
Tell about the lifecycle of React components (class-based and functional).
sobes.tech AI
Answer from AI
The React component lifecycle describes the sequence of stages a component goes through from creation to removal.
Class Components
Main lifecycle methods:
- constructor(props) — initializes state and binds methods.
- componentDidMount() — called after the component is mounted in the DOM, usually used for API requests.
- shouldComponentUpdate(nextProps, nextState) — optimizes re-rendering by returning true/false.
- componentDidUpdate(prevProps, prevState) — called after the component updates.
- componentWillUnmount() — cleans up resources before the component is removed.
Example:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log('Counter updated');
}
}
componentWillUnmount() {
console.log('Component will be removed');
}
render() {
return <div>{this.state.count}</div>;
}
}
Functional Components
With hooks, lifecycle is managed via useEffect:
useEffect(() => { ... }, [])— similar tocomponentDidMount.useEffect(() => { ... })— called after every render.useEffect(() => { ... }, [deps])— called when dependencies change.- The cleanup function returned from
useEffectis similar tocomponentWillUnmount.
Example:
function MyComponent() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('Component mounted');
return () => {
console.log('Component will be removed');
};
}, []);
React.useEffect(() => {
console.log('Counter updated:', count);
}, [count]);
return <div>{count}</div>;
}