Master React Lifecycle: Hook Functions Explained with Code Examples
This article walks through the three phases of the React component lifecycle—initialization, running, and destruction—detailing each hook function, their purposes, and performance tips, and provides a complete code example to illustrate their usage.
React Lifecycle
If we compare React's lifecycle to an ant crawling along a rope, each point the ant reaches triggers a different hook function. The following sections detail every lifecycle hook and its role.
Initialization Phase
1. Set default props static defaultProps = { name: 'sls', age: 23 }; 2. Set initial state constructor() { super(); this.state = { number: 0 }; } 3. componentWillMount()
Triggered right before the component is rendered; suitable for starting timers or sending requests.
4. render()
Renders the component's UI.
5. componentDidMount()
Called after the component is mounted to the DOM, allowing DOM‑related operations.
Running Phase
1. componentWillReceiveProps()
Invoked when the component receives new props.
2. shouldComponentUpdate()
Runs when new props or state are received (not on the initial render) to decide whether the component should re‑render.
shouldComponentUpdate(newProps, newState) { if (newProps.number < 5) return true; return false; }Developers often use this hook to improve performance by preventing unnecessary renders. For example, React’s PureComponent performs a shallow comparison of props and state and skips re‑rendering when they are unchanged.
3. componentWillUpdate()
Triggered right before the component updates.
4. componentDidUpdate()
Called after the component has updated and the new DOM is available for manipulation.
Destruction Phase
componentWillUnmount()
Fires when the component is about to be removed, allowing cleanup such as clearing timers or unsubscribing from Redux.
Full Example Code
import React from 'react';
import ReactDOM from 'react-dom';
class SubCounter extends React.Component {
componentWillReceiveProps() {
console.log('9、子组件将要接收到新属性');
}
shouldComponentUpdate(newProps, newState) {
console.log('10、子组件是否需要更新');
if (newProps.number < 5) return true;
return false;
}
componentWillUpdate() {
console.log('11、子组件将要更新');
}
componentDidUpdate() {
console.log('13、子组件更新完成');
}
componentWillUnmount() {
console.log('14、子组件将卸载');
}
render() {
console.log('12、子组件挂载中');
return (<p>{this.props.number}</p>);
}
}
class Counter extends React.Component {
static defaultProps = { name: 'sls', age: 23 };
constructor() {
super();
this.state = { number: 0 };
}
componentWillMount() {
console.log('3、父组件挂载之前');
}
componentDidMount() {
console.log('5、父组件挂载完成');
}
shouldComponentUpdate(newProps, newState) {
console.log('6、父组件是否需要更新');
if (newState.number < 15) return true;
return false;
}
componentWillUpdate() {
console.log('7、父组件将要更新');
}
componentDidUpdate() {
console.log('8、父组件更新完成');
}
handleClick = () => {
this.setState({ number: this.state.number + 1 });
};
render() {
console.log('4、render(父组件挂载)');
return (
<div>
<p>{this.state.number}</p>
<button onClick={this.handleClick}>+</button>
{this.state.number < 10 ? <SubCounter number={this.state.number} /> : null}
</div>
);
}
}
ReactDOM.render(<Counter />, document.getElementById('root'));Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
