Last active
November 19, 2020 09:06
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Full article for using componentDidMount in react hooks can be found here on the Atomized Objects blog