Using key for component identification


(Cristian Covali) #1

Most React key examples uses lists, but I am thinking to use them for re(rendering) a component.

Imaging youtube feed.
You enter youtube.com as an anonymous user and it shows you some recommended results.
After you login they show you a new set of recommended results on the same page.

If those thing would be written in React then they would need to have some kind of

class RecommendedVideoContainer extends Component {
  ...
  componentWillMount() {
    this.props.fetchRecommendedVideos();
  }

  componentWillReceiveProps(nextProps) {
    // if (nextProps.isAuthenticated !== this.props.isAuthenticated) {
         this.props.fetchRecommendedVideos();
       }
  }
  ...
}

On the other hand we can achieve the same thing by passing a auth key to RecommendedVideoContainer. Without writing an extra componentWillReceiveProps method.
Example:

render() {
  const {isAuthenticated} = this.props;

  return (
    <RecommendedVideoContainer
      key={isAuthenticated ? 'authenticated' : 'anonymous'}
      ...
    />
  );
}

How strong this impacts react app performance?


(Troy Rhinehart) #2

Your RecommendedVideoContainer still needs to be passed the isAuthenticated prop, so I don’t see how this would help with performance.

The purpose of the key from my understanding is for ordering in the DOM, such as an Array of elements. The key itself is not passed as a prop into RecommendedVideoContainer, it’s a React property.


(Pavel Hasala) #3

You are using key property for a wrong purpose. Key is to help identify elements, used for mounting/demounting. To my understanding, key is the key for react to keep track and order of elements, mostly in lists or when you are showing/hiding them. For exaple, when in form a checbox is checked, show additional content, or you are switching between two elements at the same place, so their props are not messed up.

class Component extends React.PureComponent {
	render() {
		return [
			<div key="content">
				{
					this.props.authorized
						?
							<P key="text-1" color="red" text="some text" />
						:
							<P key="text-2" color="blue" text="other text" />
				}
			</div>,
			<footer key="footer">Footer</footer>
		]
	}
}