Please go to this codesandbox example to and understand and reproduce the issue below.
- Context
I am using Ag Grid to do server side pagination on a public paginated API (Pokemon one) as explained here, and display result in the table.
Moreover, I want to be able to select an item in the table, and display all selected items at the top (stored in React state
).
- Issue
My issue is : if you change the page (for example 2nd one), and select an item in the table by clicking on it, the Grid
component is re-rendered, and you are redirected to the first page! We should stay on the second page, no reason to re-render.
- Temporary fix
I have managed it by using useCallback()
on addItem
function with empty dependency array, and memo
on Grid
component. But a new isue arises : eslint rule "exhaustive deps" is broken and we can have duplicated in the selected items list, that I want to avoid.
Any ideas how to handle that issue properly in React? Thank you!
2
Answers
You should change as below:
setSelectedItems((items) => […items, item]);
setState should always be a new object instead of mutating the original one.
}, []); // try to put selectedItems : not working anymore