'Remove a component from react hook array

There is this hook array

export interface ordenesCliente  {
  item:string
  type:string
  status:string
  
}

const [arregloOrdenesCliente, setArregloOrdenesCliente] =  useState <ordenesCliente []> ( [])

So, if the array has a length bigger than 1. To remove an item I did:

 var arrayAux: ordenesCliente[]=  []

          for (var i=0; i< props.arregloOrdenesCliente.length; i++){
            if(i!=props.positionToDlelete){
              arrayAux.push(props.arregloOrdenesCliente[i])

            }
          }
          props.setArregloOrdenesCliente(arregloAux)

But it give me doom react problems. I do not use splice because it is not a good practice for react. What can I do?



Solution 1:[1]

Use a function that doesn't mutate the original state, like this:

const removeElement(arr, index) => [...arr.slice(0, index), ...arr.slice(index + 1);

// Then
setArregloOrdenesCliente(removeElement(arregloOrdenesCliente, 4))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 windowsill