Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
DOM still shows items which are have already been deleted from state in React using hooks

I am using react-dnd (Drag and Drop) to drop in items into a div which acts as a canvas for holding the items. Since I was having trouble with dnd not updating the reference of the canvas state, I had to use an useRef hook to manually update the same.

const [canvas, setCanvas] = useState([])
const canvasRef = useRef(null);

//Function to update the referrence
const _setCanvas = (Canvas) => {
    canvasRef.current = Canvas;
    setCanvas(Canvas);
};


const [{ isOver }, drop] = useDrop(() => ({
    accept: "formElement",
    drop: (item) => {
        addElementToCanvas(item.id, generateUUID());
    },
    collect: (monitor) => ({
        isOver: !!monitor.isOver(),
    }),
}));

//Function to add element on to the canvas
const addElementToCanvas = (id, uuid) => {
    const formElement = formElements.find((element) => id === element.id);
    //Add up the necessary details required for the element
    formElement.question = "Type your question here";
    if (!formElement) {
        return;
    }
    if (canvasRef.current === null) {
        canvasRef.current = [];
    }
    const formAreaElements = [...canvasRef.current, { ...formElement, uuid: uuid }];        
    _setCanvas(formAreaElements);
    setfilled(true);
};
const removeElementfromCanvas = (formElement) => {
    const updatedForm = canvas.filter((element) => element.uuid != formElement.uuid)
    _setCanvas(updatedForm);

};

Adding items to the canvas works fine. However while deleting a particular item by its uuid, the state is updated with the rest of the items. But on the DOM, the last item which has been added gets removed, and not the one which has already been deleted from the state.

<div
  className="bg-gray-800 w-full h-screen z-1   overflow-y-auto text-white "
  ref={drop}
>
  {filled &&
    canvasRef.current.map((element, idx) => {
      return (
        <li key={idx} className="mt-8 cursor-default  w-full ">
          <FormElementHolder
            questionNo={idx + 1}
            element={element}
            removeElement={() => removeElementfromCanvas(element)}
            canvasRef={canvasRef.current}
            _setCanvas={_setCanvas}
          />
        </li>
      );
    })}
</div>;

Thanks in advance!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your element already has an id, it's better to use that instead.
Generally it's a bad practice to use indexes as keys and in this instance it is causing an error.
Index changes when you delete an item and therefore the dnd library can’t recall proper references.
This article is great one to check : https://dev.to/shiv1998/why-not-to-use-index-as-key-in-react-lists-practical-example-3e66

<div
  className="bg-gray-800 w-full h-screen z-1   overflow-y-auto text-white"
  ref={drop}
>
 {filled &&
 canvasRef.current.map((element, idx) => {
  return (
    <li key={element.id} className="mt-8 cursor-default  w-full ">
      <FormElementHolder
        questionNo={idx + 1}
        element={element}
        removeElement={() => removeElementfromCanvas(element)}
        canvasRef={canvasRef.current}
        _setCanvas={_setCanvas}
      />
    </li>
  );
})}
;
about 4 years ago · Juan Pablo Isaza Report

0

You can't reliably use indexes as keys when you're modifying the array like that. Details in this article linked from the React documentation. The problem is that on re-rendering, React thinks it can keep/reuse the DOM element for the previous thing at that index when you give it something new with that same index as its key.

You seem to have an id on the elements, so use the id as the key.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!