0

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?

Will Kanga
  • 652
  • 1
  • 6
  • 12

2 Answers2

2

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.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
0

This can be reproduced using the useEffect hook. The if you set the dependency array to contain the prop(s) you are looking for, then it will run only when that prop changes.

To do so, you'll need to convert it to a functional component instead of a class-based component.

Example:

import React from 'react'

Function ComponentName(props){
  React.useEffect(() => {
    // Code inside here will run when anything in the dependency array changes
  }, [prop.propName])  //<---Dependency array.  Will watch the prop named "propName" and run the code above if it changes.

  return (
    //Your JSX
  )
}
ckesplin
  • 1,284
  • 1
  • 9
  • 15