Say I have a component that gets an array, and I want to do some logic:
const MyComponent = ({ myArray = [] }) => {
console.log("infinite rendering");
const [prop, setProp] = useState([])
useEffect(() => {
setProp(myArray.map(x => x + 1))
}, [myArray])
return <div />
}
https://codesandbox.io/s/x3kq907r5z
The problem is I get an infinite loop.
I can fix the bug by removing the default value ({ myArray }) and checking if array if (Array.isArray(myArray)) setProp(...)
But I'm struggling to understand: What is the best way of doing any sort of manipulation to a prop (array/object/etc) using hooks?