I have a doubt from the React Router docs where it says "the history object is mutable" and gives an example as below:
The history object is mutable. Therefore it is recommended to access the
location
from the render props of<Route>
, not fromhistory.location
. This ensures your assumptions about React are correct in lifecycle hooks. For example:class Comp extends React.Component { componentDidUpdate(prevProps) { // will be true const locationChanged = this.props.location !== prevProps.location; // INCORRECT, will *always* be false because history is mutable. const locationChanged = this.props.history.location !== prevProps.history.location; } } <Route component={Comp} />;
In the above example code, shouldn't it be ===
instead of !==
at both the places?
CodePudding user response:
"Mutable history
" means that you have only 1 history
object which is then being mutated(e.g. changed) after it's created. This means if you use the history
object in the future for comparison like the following, you will always receive false
. This is because this.props.history
and prevProps.history
point to the same and only history
object(e.g they're equal). More about object comparison here :)
// INCORRECT, will *always* be false because history is mutable.
const locationChanged =
this.props.history.location !== prevProps.history.location;