component mount react hooks code example
Example 1: component did mount in hooks
For componentDidMount
useEffect(() => {
}, []);
For componentDidUpdate
useEffect(() => {
}, [yourDependency]);
For componentWillUnmount
useEffect(() => {
return () => {
}
}, [yourDependency]);
Example 2: useeffect componentdidmount
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
);
}
Example 3: componentwillunmount hooks
useEffect(() => {
window.addEventListener('mousemove', () => {});
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])
Example 4: useeffect on update
const isInitialMount = useRef(true);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
} else {
}
});
Example 5: componentdidmount in hooks
useEffect(() => {
}, []);