So typically a React component only re-renders when the state changes – but what if for some reason you want to have the component re-render when you pass it new props? Remember… State is local to the component, but props are passed down from the parent component to the child. The beauty of React is that there is only a unidirectional flow of data.

So how do we get a child to re-render when it’s passed in new props?

Enter the key attribute. React uses that to determine whether or not a re-render should occur. In its most pure form this is what we’re looking to implement:

<div key={your_updated_id>Some content...</div>

And for a more verbose example that really spells out how this is intended to be implemented. Your parent component:

import React, {Component} from 'react'
import ChildComponent from 'ChildComponent'

class MyComponent extends React.Component {
  state = {
    weather: "sunny",
    station_id: 1234
  }

  render(){
    return(
      <ChildComponent current_weather={this.state.weather} station_id={this.state.station_id} />
    )
  }
}

Your child component, which we imported in the above parent component:

import React from 'react'

const ChildComponent = (props) => {
  return(
    <div key={props.station_id}>
      The current weather outside is {props.current_weather}
    </div>
  )
}

export default ChildComponent

In the above child component, we’ve returned a <div> with a key attribute set to {props.station_id}. This way whenever the state of the parent component updates, it then pushes the updated state into the child component via its props. The child component then in turn re-renders because it received a new key.

I’d consider this use case rather contrived in the sense that it’s more or less an anti-pattern and really goes against the essence of React. Though I can see when developing a smaller app there might be a viable argument to be made when you can implement something like the above for a one-off scenario as opposed to implementing something more complex like Redux to manage the global state.