REACT
React Lifecycle Methods: Syntax, Usage, and Examples
React lifecycle methods control how components behave from creation to destruction. They let you manage updates, handle side effects, and clean up resources.
How to Use React Lifecycle Methods
React components follow a lifecycle divided into three main phases:
- Mounting: The component is created and inserted into the DOM.
- Updating: The component re-renders due to state or prop changes.
- Unmounting: The component is removed from the DOM.
Mounting Phase
Mounting methods run when a component first appears on the page.
import React, { Component } from "react";
class Example extends Component {
constructor(props) {
super(props);
console.log("Constructor: Initializing state");
}
componentDidMount() {
console.log("componentDidMount: Component is now in the DOM");
}
render() {
return <p>React Lifecycle Example</p>;
}
}
Updating Phase
Updating methods run when a component's props or state change.
class UpdatingExample extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log("componentDidUpdate: State changed");
}
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increase</button>
</div>
);
}
}
Unmounting Phase
The componentWillUnmount method cleans up before a component is removed.
class UnmountExample extends Component {
componentWillUnmount() {
console.log("componentWillUnmount: Cleanup before removal");
}
render() {
return <p>This component will unmount soon.</p>;
}
}
When to Use React Lifecycle Methods
Lifecycle methods help manage:
Fetching Data
Use componentDidMount to fetch data when the component appears.
class FetchData extends Component {
state = { data: null };
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => this.setState({ data }));
}
render() {
return <p>{this.state.data ? this.state.data.title : "Loading..."}</p>;
}
}
Updating the DOM After Render
Use componentDidUpdate to update the DOM after a re-render.
class UpdateTitle extends Component {
state = { text: "Hello" };
componentDidUpdate() {
document.title = this.state.text;
}
changeText = () => {
this.setState({ text: "Updated Title" });
};
render() {
return <button onClick={this.changeText}>Change Title</button>;
}
}
Cleaning Up Resources
Use componentWillUnmount to remove event listeners or stop API calls.
class Timer extends Component {
componentDidMount() {
this.interval = setInterval(() => console.log("Tick"), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
console.log("Interval cleared");
}
render() {
return <p>Timer running...</p>;
}
}
Examples of React Lifecycle Methods
Tracking State Changes
Use componentDidUpdate to log state changes.
class StateLogger extends Component {
state = { clicks: 0 };
componentDidUpdate(prevProps, prevState) {
if (prevState.clicks !== this.state.clicks) {
console.log(`Click count updated: ${this.state.clicks}`);
}
}
increment = () => this.setState({ clicks: this.state.clicks + 1 });
render() {
return <button onClick={this.increment}>Click me</button>;
}
}
Removing Event Listeners
Unregister event listeners in componentWillUnmount.
class WindowResizeLogger extends Component {
handleResize = () => console.log("Window resized");
componentDidMount() {
window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
render() {
return <p>Resize the window and check the console.</p>;
}
}
Managing Component Re-Renders
Control whether a component should update using shouldComponentUpdate.
class PreventUnnecessaryRender extends Component {
shouldComponentUpdate(nextProps) {
return nextProps.value !== this.props.value;
}
render() {
console.log("Component rendered");
return <p>{this.props.value}</p>;
}
}
Learn More About React Lifecycle Methods
Lifecycle Methods in React
React provides several lifecycle methods:
- Mounting: constructor(), componentDidMount(), render().
- Updating: componentDidUpdate(), shouldComponentUpdate(), getDerivedStateFromProps().
- Unmounting: componentWillUnmount().
React Component Lifecycle Methods
Functional components use hooks like useEffect instead of class lifecycle methods.
import { useState, useEffect } from "react";
function FunctionalComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Component mounted");
return () => {
console.log("Component unmounted");
};
}, []);
return <button onClick={() => setCount(count + 1)}>Increase</button>;
}
All React Lifecycle Methods
While class components have several lifecycle methods, React 16.3+ introduced new ones:
- getDerivedStateFromProps: Runs before rendering, allowing state updates based on props.
- getSnapshotBeforeUpdate: Captures the component’s state before updating the DOM.
Example of getSnapshotBeforeUpdate:
class ScrollTracker extends Component {
getSnapshotBeforeUpdate(prevProps, prevState) {
return document.documentElement.scrollTop;
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log("Previous scroll position:", snapshot);
}
render() {
return <p>Scroll and check the console.</p>;
}
}
React lifecycle methods help manage component behavior at different stages. With class components, they provide powerful control, while functional components rely on hooks like useEffect. Understanding lifecycle methods ensures smoother application performance and better state management.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.