In the two following versions of the same component, one functional and the other class-based, what's the difference, if any, between the code in the body of the function and the code in the body of componentDidMount
in the class case?:
function Foo(props) {
// some code goes here ...
return <h1>Foo</h1>;
}
class Foo extends React.Component {
componentDidMount() {
// code goes here ...
}
render() {
return <h1>Foo</h1>;
}
}
I'm still a bit confused about the difference between mounting vs rendering, so if it's relevant, remarks about this may also be helpful.
Code in the componentDidMount function can expect that the component has been added into the tree. Code outside of will at least be called once while component is not yet mounted. This is true for the functional component as well as code in the render function before the return in the class component.
componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
Why is this needed? There are some cases where you want to trigger certain functions only after the component has mounted. Take for example using a ref on a element to change its color. The ref will only be set after it was mounted / rendered.
For functional components you can use the useEffect hook to replace componentDidMount functionality.
See: https://reactjs.org/docs/react-component.html#componentdidmount and https://reactjs.org/docs/hooks-effect.html
It is very helpful to also understand the react class component life cycle:
See: https://busypeoples.github.io/post/react-component-lifecycle/