I have this piece of code in my react component:
const [editOrderComponentKey, setEditOrderComponentKey] = useState(0)
// clear/reload EditOrderPanel on a freshly loaded order
useEffect(() => {
setEditOrderComponentKey(editOrderComponentKey + 1)
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, [singleOrder])
the purpose of the code above, is to change the editOrderComponentKey when singleOrder has changed. I cannot put the editOrderComponentKey in the dependencies list, as the linter asks, because it will cause an infinite rendering, easy to see why.
anyway, this effect comes handy because few lines below I have the following code:
<EditOrderPanel orderId={orderId} key={`editOrder${editOrderComponentKey}`}/>
I want to invalidate EditOrderPanel if and only if singleOrder changes, so that EditOrderPanel would be re-mounted, and EditOrderPanel‘s local state would get its defaults anew (useState default).
is there a way to design the code such that no linter disablement would be required on that line, and still being able to use uncontrolled components?
>Solution :
In this case you can use the callback version to get the previous value.
const [editOrderComponentKey, setEditOrderComponentKey] = useState(0)
useEffect(() => {
setEditOrderComponentKey(prev => prev + 1)
}, [singleOrder, setEditOrderComponentKey])