In this talk https://reactjs.org/docs/hooks-intro.html the speaker write codes that resemble this :
class SomeComponent extends React.Component {
constructor(props){
super(props)
this.handleResize.bind(this)
}
handleResize(){
//do something with window.innerWidth
}
componentDidMount(){
window.addEventListener('resize',this.handleResize)
}
}
Why is the window.addEventListener
part in componentDidMount ? Does it have to be ?
From the tone of the talk, I felt that this situation was pretty common.
I'm fairly new to react, and I would have put the browser api event subscription in the constructor just as well.
Is there any advantage that would have elude be as to why put this window.addEventListener
in componentDidMount ? Or is it juste for readability purposes ?
To me it's quite simple.
First, you only want api call or event listeners to be called/initialised only once, componentDidMount()
and constructor
is guaranteed to run only once per mounted component.
However, I won't put api in constructor because if you want a UI update after your data is returned from the api, you need a state change, while you cannot set state in constructor
. The only place that only run once and allow you to setState is componentDidMount()
.
For Event listeners I think it can be put in constructor
/componentDidMount
. However, the official docs do recommend that to be put in componentDidMount()
. Have a look at this.
componentDidMount is called after the component is mounted and has a DOM representation. This is often a place where you would attach generic DOM events.