Official Case
Starting with the official example provided above, immutability-helper has been used with its update function. It performs the task of sorting items in an array upon dragging and dropping an item.
_12import update from 'immutability-helper'_12_12const moveCard = useCallback((dragIndex: number, hoverIndex: number) => {_12 setCards((prevCards: Item[]) =>_12 update(prevCards, {_12 $splice: [_12 [dragIndex, 1],_12 [hoverIndex, 0, prevCards[dragIndex] as Item],_12 ],_12 }),_12 )_12}, [])
Typescript Case
Another ergonomic solution to consider would be immer. immer allows you to deal with immutable state in a more direct way with the produce function. Like the previous method, it enables drag-and-drop operations while still ensuring immutability.
_27import { clone } from 'lodash'_27_27function immutableSplice(_27 array: IObservableArray<Item>,_27 splices: [[number, number], [number, number, Item]],_27) {_27 const clonedArray = clone(array)_27_27 splices.forEach((spliceArgs) => {_27 if (spliceArgs.length === 3) {_27 clonedArray.splice(...spliceArgs)_27 } else {_27 clonedArray.splice(...spliceArgs)_27 }_27 })_27_27 return clonedArray_27}_27_27const moveCard = useCallback((dragIndex: number, hoverIndex: number) => {_27 setCards((prevCards: Item[]) =>_27 immutableSplice(prevCards, [_27 [dragIndex, 1],_27 [hoverIndex, 0, prevCards[dragIndex] as Item],_27 ]),_27 )_27}, [])
Immer Case
Another ergonomic solution to consider would be immer. immer allows you to deal with immutable state in a more direct way with the produce function. Like the previous method, it enables drag-and-drop operations while still ensuring immutability.
_10import { produce } from 'immer'_10_10const moveCard = useCallback((dragIndex: number, hoverIndex: number) => {_10 setCards((prevCards: Item[]) =>_10 produce(prevCards, (draft) => {_10 draft.splice(dragIndex, 1)_10 draft.splice(hoverIndex, 0, prevCards[dragIndex])_10 }),_10 )_10}, [])
Conclusion
While immutability-helper is a useful tool for handling immutable data, both lodash and immer suggest simpler and more straightforward alternatives, especially with TypeScript. It's important to remember that using such libraries to maintain immutability can simplify debugging and enhance your React application's performance.