Search code examples
reactjsdrag-and-dropdnd-kit

Weird infinite rerender behaviour with nested dndkit SortableContext


I'm currently trying to build a trello-like application with lists and tasks. I wanted to incorporate drag n drop functionality so I added the dndkit library. I've managed to make the tasks sortable between the lists, and I would like to make the lists sortable aswell. However when I try to nest DndContext and SortableContext the application sometimes enters a weird recursive re-render loop and throws the following error repeatedly:

`Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.`

The application then proceeds adds an undefined task into the data and fails when it maps over the data to re-render. I've tried logging to see where the error might be but I was only able to figure out the addition of the undefined, not the source of it or the re-render loop.

Here is the current code I have, and here the repo with both branches.

Here is a video demonstrating the issue: https://imgur.com/a/HzRCK9B


Solution

  • that's possibly due to how close your columns are to each other and the size of the dragging element is causing it to detect two columns at the same time. You have "closestCorner" as the strategy for detection and it's most likely detecting two areas at the same time causing the set state dispatch to call infinitely.

    This is some of the issues that I've found while using dnd-kit is that moving items across containers requires you to setState during handleDragOver and imo, I don't really like this since changing state while dragging can cause a lot of issues.

    There are a few ways that you can solve this you can either

    1. don't use handleDragOver to move between columns and only use handleDragEnd to setState. But this means that you'll lose all those nice animation that you have there. In handleDragOver, you can then make your own styling to indicate hover over a column/card (this is not the most beautiful way but it should fix your problem)

    2. Have a better collision detection logic (there are examples in Storybook of dnd-kit). You can try to setup a custom collision detection strategy by using a combination of it. Eg. pointerWithin, closestCenter, closestCorner, rectSect.

    Doing either of these will mitigate your issues but what I noticed when using your code is that if you drag repeatedly over different columns you will get an infinite loop because of how often setState action is called. So I'm not really sure if there is a way to fix this to be honest. But I hope this helps explain you the issue a little further.