I am coming over from class styled React components and learning hooks. Can I just use useEffect
how I would would use componentDidMount
lifecycle method? For example, can I import a function and just call it within useEffect()
to mimic how componentDidMount
would work?
import { myFunc } from './importedFuncs';
export default function User() {
useEffect(() => {
myFunc();
});
To have an useEffect
equivalent to componentDidMount
, use the empty array []
as the second argument. An empty dependency list ensures the function is executed just once, on the first render.
You can use useEffect(() => {//some code}, [])
to mimic the old componentDidMount
function. some code
will only run once on the first render. You can read this article to better understand the useEffect
hook.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.