React Parent state update wiping child state
My InventoryCard (parent) component has an 'isHovered' state being set by an onMouseEnter/Leave event listener.
Its child, ImgSlider receives isHovered as a prop. So when isHovered changes, both InventoryCard & ImgSlider will be re-rendered, reflecting its new value.
ImgSlider has its own state, 'visualIndex', which is updated by interacting with it (clicking arrows) which happens while the parent is still being hovered & isHovered is still true.
After I've reset the child's visualIndex state, I then un-hover the parent InventoryCard, causing isHovered to go back to false and a re-render of the parent (and child) occurs again.
This time, when the child ImgSlider is re-rendered, its visualIndex state gets set back to '0' instead of still reflecting the change.
So the child is keeping its state so long as the parent's state (isHovered) doesn't change, but once isHovered get reset to false again, the child's visualIndex state is wiped and re-'mounted'(?) from scratch, whereas I want it to be retained.
GH: https://github.com/nndesigns/old_cars_ltd.git
--- working on deployment
GitHub
GitHub - nndesigns/old_cars_ltd: Sample car site Old Cars Ltd
Sample car site Old Cars Ltd. Contribute to nndesigns/old_cars_ltd development by creating an account on GitHub.


2 Replies
saw your code and it's little messy
what you are doing is called "prop drilling" where you get prop and you send it to and child then another child and so on
try using context to get the state you want to all your components at once
Yep like Muneer said, try
useContext
. useReducer
could work too