Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  86] [ 7]  / answers: 1 / hits: 6803  / 2 Years ago, fri, march 11, 2022, 12:00:00

I have a function which is technically a React Functional Component:


export default function Daw() {
return (
<>
<div>Hello world.</div>
</>
);
}

Of course, my ordinary function cannot have the ReactJS method of componentDidMount(). Since it is not a class which extends React.PureComponent.


I'm using this function inside a ReactJS web app.


export default function Daw() {

componentDidMount() { // ** Cannot use this ReactJS method!?
}

return (
<>
<div>Hello world.</div>
</>
);
}

Question


How can I possibly call componentDidMount() method of ReactJS inside my ordinary function? Is there a way to do it, without converting my function to a class which extends React.PureComponent? Is it possible?


More From » reactjs

 Answers
1

You're going to need React Hooks! All life-cycle methods we were doing in class components are available in functional components too via React Hooks, even in a better way. Read more about React hooks here: https://reactjs.org/docs/hooks-intro.html


And in this case, the equivalent of componentDidMount is this:


import { useEffect } from 'react'

export default function Daw() {
useEffect(() => {
// Code here will run just like componentDidMount
}, [])

return (
<>
<div>Hello world.</div>
</>
)
}

You can also learn about Effects in React by reading my article: A Beginner’s Guide to Effects in React


[#285] Tuesday, March 1, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
patienceannel

Total Points: 674
Total Questions: 101
Total Answers: 101

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
patienceannel questions
;