componentDidMountcomponentWillUnmount
ComponentDidMount and componentWillUnmount are lifecycle methods in React, a popular JavaScript library for building user interfaces. These methods are used to manage side effects in functional components, which are operations that affect something outside of the component, such as fetching data, subscribing to events, or manually changing the DOM.
ComponentDidMount is invoked immediately after a component is mounted, meaning it has been inserted into the
class MyComponent extends React.Component {
this.setState({ data });
});
}
render() {
// ...
}
}
ComponentWillUnmount is called just before a component is unmounted and destroyed. This method is used to
class MyComponent extends React.Component {
this.dataFetch = fetchData().then(data => {
this.setState({ data });
});
}
}
}
render() {
// ...
}
}
In functional components, the useEffect hook can be used to achieve similar results. The first argument
useEffect(() => {
const dataFetch = fetchData().then(data => {
});
return () => {
}
};
}, []);
// ...
}