ComponentDidMount:
componentDidMount()
is a lifecycle method in React that is called after a component has been added to the DOM. It’s a good place to make API calls or set up subscriptions, since the component is guaranteed to have been rendered and have access to the DOM.
useEffect:
useEffect
is a Hook in React that allows you to synchronize a component with an external system. It serves a similar purpose as componentDidMount()
, componentDidUpdate()
, and componentWillUnmount()
lifecycle methods combined.
Example of componentDidMount in Class Component:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
fetch(`https://api.example.com/data/${this.props.id}`)
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
return (
<div>
<h1>My Data</h1>
<ul>
{this.state.data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
}
Example of useEffect in Functional Component:
import { useEffect, useState } from 'react';
function MyComponent({ id }) {
const [data, setData] = useState([]);
useEffect(() => {
fetch(`https://api.example.com/data/${id}`)
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
<h1>My Data</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
In both examples, the API call is made when the component is first mounted to the DOM, and the fetched data is used to render the component. The main difference is that in the class component, the API call is made in the componentDidMount()
lifecycle method, and in the functional component, the API call is made using the useEffect
hook.
It’s important to note that useEffect
is more powerful than componentDidMount
as it allows to do more things like listen to events, handle cleanup, and run effects on prop changes.