I can't get my head wrapped around this behavior. In the console log message of the App component, arr shows as an array with 2 element as expected. However, when it's passed down to the ChildComponent, it shows as an empty array. If instead of using splice on the pokemon array directly, I first spread it to a new array, and then use splice on that, it works fine.
Obviously it's because splice changes the array directly, which goes against React rule of immutability, but I cant figure out why that matters when the pokemon array isn't what being passed to the child component.
const pokemon = [
{
name: 'pikachu'
},
{
name: 'raichu'
}
]
export default function App() {
const arr = pokemon.splice(0,2)
console.log(arr)
return (
<div className="App">
<ChildComponent example={arr} />
</div>
);
}
const ChildComponent = (props) => {
console.log(props);
return (
<div>
hi
</div>
)
}
The actually reason you face this strange behavior is because your code App
is wrapped with StrictMode that renders your component twice.
Splice at first returns the removed items, then pokemon has none left after first splice. arr
prints these remove items. Because you app is wrapped with StrictMode
(app gets executed again), pokemon (which now is an empty array) gets spliced again, and Child has an empty array printing an empty array.
If you remove StrictMode
wrap, your code will behave as expected and both console.log
will print correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With