lifecycle rendering in functional component are managed through effect
For a class component, see class lifecycle method
Demo:
function LifeCycle(props) {
const [updateCount, setUpdateCount]= React.useState(0);
React.useEffect(() => {
console.log("Effect function has run - same life-cycle as componentDidMount and componentDidUpdate");
// Specify how to clean up after this effect:
return function cleanup() {
console.log("Cleanup Effect function has run - same life-cycle as componentWillUnmount");
};
});
function handleClick(e) {
setUpdateCount(updateCount+1);
}
return (
<div>
<h2>LifceCycle Component</h2>
<p>The lifecycle Component sees {props.count} clicks and {updateCount} update count.</p>
<p>An update mounts and unmounts (cleanup). Try it by clicking below</p>
<button type="button" onClick={handleClick}>Update the component</button>
</div>)
}
function App() {
const [toggle, setToggle]=React.useState(false);
const [count, setCount]=React.useState(0);
function handleClick(e) {
setToggle(toggle ? false : true);
setCount(count+1);
}
let cycle = null;
if (toggle) {
cycle = <LifeCycle count={count}/>;
}
return (
<div>
<h1>Mount/Unmount/Update Demo</h1>
<button type="button" onClick={handleClick}>{toggle ? 'Unmount the lifecycle component' : 'Mount the lifecycle component'}</button>
{cycle}
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->
</div>