Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

are missing dependencies in useEffect *always* mean bad design?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading