Reputation: 21
can we use the life cycle method in the function component? Does vise versa life cycle hook in-class component? If yes, How, Please Share any link on same.
Upvotes: 2
Views: 1239
Reputation: 443
Yes, you can use the life cycle method in the functional component with help of useEffect
hooks.
useEffect
hook can be used to replicate lifecycle behavior. For example:
componentDidMount:
componentDidMount() {
window.addEventListener('unhandledRejection', handler);
}
Equivalent in functional component
useEffect(() => {
window.addEventListener('unhandledRejection', handler);
}, [])
componentWillUnmount:
componentWillUnmount() {
alert('The component is going to be unmounted');
window.removeEventListener('unhandledRejection', handler);
}
Equivalent in functional component
useEffect(() => {
window.addEventListener('unhandledRejection', handler);
return () => {
alert('The component is going to be unmounted');
window.removeEventListener('unhandledRejection', handler);
}
}, [])
componentDidUpdate:
componentDidUpdate(prevProps, prevState) {
const { counter } = this.props;
if (this.props.counter !== prevState.counter) {
// some action here
}
}
Equivalent in functional component
useEffect(() => {
// action here
}, [props.counter]); // checks for changes in the values in this array
Upvotes: 4