I have this react component that is not an ES6 class
. It's a const
like :
import React from 'react';
import Dashboard from './components/Dashboard';
const Home = (props) => {
const componentDidMount = () => {
console.log('component mounted'); // not working
}
return <Dashboard />;
}
Inside this const how do i define the componentDidMount
function like i would do in a normal ES6 class
? this is how i did it before.
import React from 'react';
import Dashboard from './components/Dashboard';
class Dashboard extends React.Component {
componentDidMount() {
console.log('component mounted');
}
render() {
return <Dashboard />;
}
}
To anyone else learning React and stumbling upon this in the future like me, the accepted answer here is out of date. Please see this question: componentDidMount equivalent on a React function/Hooks component?
If using React 16.8.0+ you can create the effect of componentDidMount by using the hook useEffect
:
useEffect(() => {
// Your code here
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With