Today I Learned

hashrocket A Hashrocket project

Simulate componentDidMount with a useEffect

If you want to simulate a componentDidMount class method inside your functional component, you can use the useEffect hook thusly:

const MyFunctionalComponent = () => {
   useEffect(() => {
     // any code here is run once 
   }, []); 
   // the empty array will be the same each 
   // time the component is called, so the useEffect
   // will not run in calls subsequent to the first
   return <div>Foo</div>;

ht: @greis

See More #react TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.