This question relates to an implementation detail of React, more specifically, to state encapsulation.
The demo in this answer to this question demonstrates that React props that are objects are passed by reference, reproduced here:
const Parent = () => {
let myInt = 1;
let myObj = {a: "foo"};
setTimeout(function(){
myInt = 2;
myObj.a = "bar";
}, 500);
return <Child myInt={myInt} myObj={myObj} />;
}
const Child = ({myInt, myObj}) => {
setTimeout(function(){
console.log(myInt);
console.log(myObj);
}, 1000);
return (
<div>
<p>{myInt}</p>
<p>{JSON.stringify(myObj)}</p>
</div>
);
}
ReactDOM.render(<Parent />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
It is possible in React to pass state as a prop to a child component. Given that objects/arrays props are passed by reference, how is state encapsulation maintained by React?
Does the child component locally copy the props that are passed to it? Thereby the child component does not care about the origin of the prop is state (i.e. avoids the risk of state changing at the level of parent component being reflected in the prop that is passed to the child component).