Skip to content

Instantly share code, notes, and snippets.

@WillMayger
Last active November 19, 2020 09:06
Show Gist options
  • Save WillMayger/03f04be7a3697549e62baef6343a62d7 to your computer and use it in GitHub Desktop.
Save WillMayger/03f04be7a3697549e62baef6343a62d7 to your computer and use it in GitHub Desktop.
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)
}
})
}
@WillMayger
Copy link
Author

WillMayger commented Nov 19, 2020

Full article for using componentDidMount in react hooks can be found here on the Atomized Objects blog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment