0
votes

I've read that componentDidMount runs after render in React components, but I'm still a bit confused. Let's say I'm making a request in componentDidMount to an API to populate my state, but if render runs before componentDidMount, how is my application displaying the information to the user? Is the React component doing something like render() -> componentDidMount() -> render()? And if so, what is the benefit to running render() before componentDidMount()?

1
componentDidMount() does not block rendering. At minimum you can handle it by having conditional rendering logic to show some sort of loading message until the data is available and has been updated in state. And/or use logical default values for state such as an empty array for list/array data to avoid having errors caused by accessing undefined values.Alexander Staroselsky

1 Answers

1
votes

A component is rerendered when you update its state or when a prop changes. So if you update its state in componentDidMount(), then the component rerender.

ComponentDidMount exists as a way for you to know that your component is mounted, as its name says. So for example if you need to get the height of something from your jsx, you could do it here, you won't get an error saying your reference is undefined, because your component is mounted and so the node exists.