reactjs: how to define componentDidMount inside ES6 const?
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 />;
}
}
Stateless functional components don't support the lifecycle methods.
You can either convert it to a stateful component or wrap it in a stateful container.
Good example of wrapping to get the lifecycle methods:
https://egghead.io/lessons/javascript-redux-fetching-data-on-route-change
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
}, []);