Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would a react component not be a pure component?

just been reading this: https://reactjs.org/docs/react-api.html#reactpurecomponent

and trying to work out when would a function not return something pure?

surely if you give a component the same props/state then it will always return the same result?

like image 902
Red Baron Avatar asked Dec 23 '22 02:12

Red Baron


2 Answers

Imagine if you had a component that showed the weather and a background image of the sun if it's daytime and a background picture of the moon if it's night.

You would pass in the temperature, wind speed etc. through props, but you would display the correct image depending on the time of day.

So, if you pass the temperature of 15 degrees during the day and during the night, the component will look differently even though you have passed the same props.

like image 177
Bojan Ivanac Avatar answered Jan 06 '23 19:01

Bojan Ivanac


If your function component has any side effects, then it would not be a pure component. For example, reading the current time via Date.now() is a side effect. If that date is passed via prop, then you're fine. But React/JavaScript cannot guarantee that a function component doesn't have side effects.

Consider the following function components.

function Impure() {
  return <p>{Date.now()}</p>
}

function Pure(date) {
  return <p>{date}</p>
}
like image 36
Raphael Rafatpanah Avatar answered Jan 06 '23 19:01

Raphael Rafatpanah