In my app, i am passing some weather data to a component as a prop and I want to have the color of the temp update based on that value. Here is what I did. It seems that react does not always re-render when a prop is changed. How can I make sure that this gets updated every time the prop changes?
const Current = (props) => {
const { weather } = props
const [color, setColor] = useState([])
useEffect(() => {
setColor(tempScheme[weather.current.temp_f])
}, [weather, color])
return (
<Container>
<CardContent>
<Header>
<Typography variant='h6'>Currently</Typography>
<Typography variant='h6'> {formatDate(props.weather.location.localtime)} </Typography>
</Header>
<Weather>
<Typography variant='h5'> {props.weather.current.condition.text} </Typography>
<Typography variant='h2' style={{"color": `rgb(${color})`}}> {Math.round(props.weather.current.temp_f)}° </Typography>
</Weather>
<Location>
<Typography variant='body1'> {props.weather.location.name}, {props.weather.location.region}</Typography>
<Image src={props.weather.current.condition.icon} />
</Location>
</CardContent>
</Container>
)
}e here
You're mixing up a few concepts here, which is breaking the implementation. On the one hand, you're passing the weather object (with color on it) as a prop, but you're also storing/referencing this in local state, and using useEffect to set this internal instance of color. In other words, you are not reacting to the changes to color from the parent component. In addition, react won't re-render if a key/value changes on an object in a parent component, only if the object itself changes. what you want to do is move your color state, and the useEffect up one level, and also adjust the dependency array of the useEffect so it subscribes to the right change, so
const [color, setColor] = useState(tempScheme[weather.current.temp_f]
and
useEffect(() => {
setColor(tempScheme[weather.current.temp_f])
}, [weather.current.temp_f])
then pass this into the child as a color prop
<Current color={color} />
Then to consume within the component itself you can just do
const current = ({ color }) => ...restOfTheComponent
alternatively, you can probably simplify this by just removing the local state and use effect, and just passing the color directly like this
<Current color={weather.current.temp_f} />