I am creating a chat app and I have a component called ChatBox. ChatBox subscribes to a WebSocket when the user clicks on a chat channel. Right now, this is done in the constructor. The issue is that I now need to let the user change channels, but constructor is not called when the props change. I could use componentDidUpdate, but I would have to compare my props against my old props on every render, which is very inconvenient.
TL; DR: I need to do something when my props get changed. I found a method called componentDidReceiveProps which fits my situation perfectly! But sadly React says that the method is bad practice, and they made it deprecated:
One of the biggest lessons we’ve learned is that some of our legacy component lifecycles tend to encourage unsafe coding practices ... These lifecycle methods have often been misunderstood and subtly misused
My question is: what is the correct way to produce the same behavior?
Use componentDidUpudate
. Check if the relevant prop changed, and if so, update the socket or do whatever else is needed.
componentDidUpdate(prevProps) {
if (this.props.channel !== prevProps.channel) {
// do stuff
}
}
but I would have to compare my props against my old props on every render, which is very inconvenient.
Yes, you do need to check that the right prop changed. You'd have to do that with componentWillReceiveProps also.