A React.js warning was thrown:
IndexPage: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.
I had the following code:
class IndexPage extends React.Component<IProps, IState> {
constructor(props) {
super(props)
this.state = props
}
}
But, when I have changed my code to:
class IndexPage extends React.Component<IProps, IState> {
constructor(props) {
super(props)
this.state = {...props}
}
}
The warning's gone.
Can you please explain why?
Because of how JS assignment of object values works, assigning one object to another means that the second variable will "point" to the same instance, or hold a reference to it:
let x = { v: 1 };
let y = x;
x.v = 2;
console.log(y.v) // prints "2"
The warning is there to prevent accidental assumptions about the props being automatically "propagated" to the state. IOW, it doesn't just work like you'd normally expect:
// assume props = { v: 1 };
this.state = props;
// now props changes to { v: 2 };
console.log(this.state.v) // still prints 1, and that's why you get the warning
The warning goes away because by destructuring, you're making it obvious that a new object is being created, and you don't expect the state to have the same value as props when they change.