component will mount react hooks code example
Example 1: replace componentwillmount with hooks
useEffect(() => {
//will be called on every load
})
useEffect(() => {
//will be called on component mount
window.addEventListener('mousemove', () => {});
// returned function will be called on component unmount
return () => {
window.removeEventListener('mousemove', () => {})
}
}, []) // <---- empty array at end will cause to only run on first load
Example 2: component did mount in hooks
For componentDidMount
useEffect(() => {
// Your code here
}, []);
For componentDidUpdate
useEffect(() => {
// Your code here
}, [yourDependency]);
For componentWillUnmount
useEffect(() => {
// componentWillUnmount
return () => {
// Your code here
}
}, [yourDependency]);
Example 3: componentwillunmount hooks
useEffect(() => {
window.addEventListener('mousemove', () => {});
// returned function will be called on component unmount
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])
Example 4: react hook will mount
const useComponentWillMount = (func: (params?: any) => any) => useMemo(func, []);