I've got a problem in my project which is pretty large therefore I can't post every part of the code here, but I'll try to summarize the main parts. I've got a parent component which state is managed through a useReducer and which render returns a mapping of this state. Each child has to take both the value and the index of the mapping. I'm also using the Context API to pass the dispatcher on some of the childs.
function ParentComponent(props) {
const [state, dispatch] = useReducer(initialData, reducer);
return (
<div>
<MyContext.Provider value={dispatch}>
{state.myArray.map((value, index) => (
<ChildComponent value={value} index={index} />
))}
</MyContext.Provider>
</div>
);
}
/* Other file */
function ChildComponent({value, index}) {
const dispatch = useContext(MyContext);
return <div>
{/* Uses value and index to display some data */}
</div>
}
export default React.memo(ChildComponent, (prevProps, nextProps) => !_.isEqual(prevProps, nextProps));
Some of the childs in the tree components have to use React.memo
to avoid useless re-renders, ChildComponent
is one of them.
I'm using the lodash functions _.isEqual
to compare the props to know when the component has to re-render.
The problem is the following. One of my components in the component tree adds items to the myArray
attribute of the ParentComponent
state.
When I add an item, anyway, each ChildComponent
rendered from the ParentComponent mapping receives the same index of 0, creating a lot of problems.
The ParentComponent
has the right indices (when I log them inside the mapping they are the right ones) but it's like the ChildComponent
isn't getting it.
Is there any way to solve this? Maybe it has something to do with React.memo
?