Lifecycle hooks for functional components
Open a Terminal in the project root and run:
yarn react-lifecycle-hook
or
npm i react-lifecycle-hook
After all the elements of the page is rendered correctly, this method is called
import { useComponentDidMount } from 'react-lifecycle-hook';
export const YourAwesomeComponent = () => {
useComponentDidMount(() => {
fetchData()
document.addEventListener("click", closeMenu);
})
return (
//...
)
}
Can be useful to perform some action when the state changes
import { useComponentDidUpdate } from 'react-lifecycle-hook';
export const YourAwesomeComponent = () => {
useComponentDidUpdate(
(prevProps) => {
if(prevProps.isOpenModal !== isOpenModal) {
console.log('Modal state changed')
}
},
{ isOpenModal },
);
return (
//...
)
}
useComponentWillUnmount is invoked immediately before a component is unmounted and destroyed
import { useComponentWillUnmount } from 'react-lifecycle-hook';
export const YourAwesomeComponent = () => {
useComponentWillUnmount(() => {
document.removeEventListener("click", closeMenu);
});
return (
//...
)
}