Using componentDidMount in react hooks - Full article on componentDidMount with react hooks found here: https://atomizedobjects.com/blog/react/using-componentdidmount-in-react-hooks/
import { useEffect, useState, useRef, useCallback } from 'react' | |
// Solutions for the article https://atomizedobjects.com/blog/react/using-componentdidmount-in-react-hooks/ | |
// about using componentDidMount in react hooks | |
export function SolutionsOneToFour() { | |
// Solution 1 | |
useEffect(() => { | |
console.log("Mounted") | |
}, []) | |
// Solution 2 | |
const someNumber = 5 | |
useEffect(() => { | |
console.log("someNumber changed to: ", someNumber) | |
}, [someNumber]) | |
// Solution 3 | |
useEffect(() => { | |
const runOnMount = () => { | |
console.log("componentDidMount react hooks") | |
} | |
runOnMount() | |
}, []) | |
// Solution 4 | |
const myMessage = "componentDidMount react hook" | |
const runOnMount = useCallback(() => { | |
console.log(myMessage) | |
}, [myMessage]) | |
useEffect(() => { | |
runOnMount() | |
}, [runOnMount]) | |
} | |
// Solution 5a | |
export function useDidMountWithoutRender(callback) { | |
const didMount = useRef(null) | |
useEffect(() => { | |
if (callback && !didMount.current) { | |
didMount.current = true | |
callback() | |
} | |
}) | |
} | |
// Solution 5b | |
export function useDidMount(callback) { | |
const [mounted, setMounted] = useState(false) | |
useEffect(() => { | |
if (callback && !mounted) { | |
callback() | |
setMounted(true) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Full article for using componentDidMount in react hooks can be found here on the Atomized Objects blog