component did mount equivalent hooks code example
Example 1: componentdidmount hooks
For componentDidMount
useEffect(() => {
// Your code here
}, []);
For componentDidUpdate
useEffect(() => {
// Your code here
}, [yourDependency]);
For componentWillUnmount
useEffect(() => {
// componentWillUnmount
return () => {
// Your code here
}
}, [yourDependency]);
Example 2: alternative for componentdidmount
import React, { useEffect } from 'react'const SampleComponent = () => { useEffect(() => { // code to run on component mount }, [])return (<div>foo</div>)}export SampleComponent
Example 3: componentdidmount in hooks
useEffect(() => {
// Your code here
}, []);