What are the equivalents of the componentDidMount
, componentDidUpdate
, and componentWillUnmount
lifecycle hooks using React hooks like useEffect
?
What are the equivalents of the componentDidMount
, componentDidUpdate
, and componentWillUnmount
lifecycle hooks using React hooks like useEffect
?
componentDidMount
Pass an empty array as the second argument to useEffect()
to run only the callback on mount only.
function ComponentDidMount() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('componentDidMount');
}, []);
return (
<div>
<p>componentDidMount: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<div>
<ComponentDidMount />
</div>,
document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>