So, as we know, the differences between Shallow Copy to Deep Copy is: shallow copy
a=5;
b=a; // b point to a's address in the memory. if a changes, b changes.
deep copy
a=5;
b=a; // b holds the actual value 5. if a changes, b remains the same.
Cool, now, my question is: Does passing states as props to children consider to be 'deep' copy or 'shallow' copy?
I tend to think it is a deep copy, and then another question raises - isn't that wasteful in resources?
Cheers!
CodePudding user response:
Passing state as props doesn't copy anything at all. The exact same value is used in both places. For a tiny example:
let parentObj;
const App = () => {
const [parentStateObj, setParentStateObj] = React.useState({ prop: 'val' });
parentObj = parentStateObj;
return <Child obj={parentStateObj} />;
};
const Child = ({ obj }) => {
console.log(obj === parentObj);
return 'foo';
};
ReactDOM.createRoot(document.querySelector('.react')).render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='react'></div>
This is somewhat similar to your comment in the first snippet that
// b point to a's address in the memory. if a changes, b changes.
except that
- No copying occurs
- If one of the values is reassigned (in the parent or child), that won't have any effect on the other value - reassigning a variable, by itself, has no side-effects
- If one of the values is mutated (in the parent or child) - while the change will be visible in both components if you set things up to observe it - you should never mutate state in React. Rather, you should call the state setter with the new state, which will then trigger a re-render.
Shallow copying usually refers to one of the following, which actually creates a separate array or object:
const shallowCopyArr = [...arr];
const shallowCopyObj = { ...obj };
Deep copying refers to recursively iterating over every nested value in an object or array to create a new one and is somewhat more complicated.