Componentdidmount To Functional Component Example


Example 1: how to use componentdidmount in functional component


// passing an empty array as second argument triggers the callback in useEffect
// only after the initial render thus replicating `componentDidMount` lifecycle behaviour
useEffect(() => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
}, []);

// componentDidUpdate
useEffect({
your code here
})

// For componentDidUpdate
useEffect(() => {
// Your code here
}, [yourDependency]);

// For componentWillUnmount
useEffect(() => {
// componentWillUnmount
return () => {
// Your code here
}
}, [yourDependency]);

Example 2: useeffect react


useEffect(() => {
window.addEventListener('mousemove', () => {});

// returned function will be called on component unmount
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android SDK Location Should Not Contain Whitespace, As This Cause Problems With NDK Tools