Here's an example from a Modal component I wrote last week. It has a prop called "dismissOnEsc" which allows the consumer to decide if hitting the ESC key will dismiss the Modal. If (for whatever dumb reason) the consumer didn't want ESC to dismiss the Modal, but later on in the components life cycle decided that it should, well then nothing would happen because the event listener is registered in componentDidMount and the component wasn't remounted, it's props just changed.
Let me warn you, this is written in TypeScript. Assuming you've only done JS in the past, you'll probably see some syntax you're not familiar with, just ignore it, it doesn't affect the way the code works, just gives you better type completions in your IDE.
So the reason why I implement that function is to register/unregister event listeners that listen for the escape key as the user passes in different props. That's what componentWillReceiveProps is for, changing things you did in componentDidMount/componentWillMount based on changes to the props.
rozzzly
Insanity at its best - github.com/rozzzly
Here's an example from a Modal component I wrote last week. It has a prop called "dismissOnEsc" which allows the consumer to decide if hitting the ESC key will dismiss the Modal. If (for whatever dumb reason) the consumer didn't want ESC to dismiss the Modal, but later on in the components life cycle decided that it should, well then nothing would happen because the event listener is registered in
componentDidMountand the component wasn't remounted, it's props just changed.Here's the relevant snippet of code:
componentWillReceiveProps(nextProps) { if (canUseDOM) { if (nextProps.dismissOnEsc && !this.props.dismissOnEsc) { this.registerEscListener(); } else if (!nextProps.dismissOnEsc && this.props.dismissOnEsc) { this.unregisterEscListener(); } } }If you need me to explain further / show you the full code, just ask, I don't mind.