Eliav2 / react-xarrows

Draw arrows (or lines) between components in React!
https://codesandbox.io/embed/github/Eliav2/react-xarrows/tree/master/examples?fontsize=14&hidenavigation=1&theme=dark
MIT License
584 stars 75 forks source link

fix: stabilize the fallback value of useXarrow #155

Closed xandris closed 1 year ago

xandris commented 2 years ago

Hello, apologies for the pull request out of the blue. react-xarrows is awesome and met an urgent need we had on our project. There are a few rough edges we'd like to work out if possible.

We've occasionally gotten into an infinite loop when putting updateXarrow in a hook dependency list. Reading the code, updateXarrow looks reference stable after effects have fired, which is great. However, before effects have fired, useXarrow() will return a new reference every render. This can lead to a render loop if updateXarrow is placed in a hook's dependency list. Stabilize it by making the fallback value a module-scope const. Keep in mind what the React documentation says about effects:

The function passed to useEffect will run after the render is committed to the screen.

React may also defer or batch renders, so reference stability is important; the identity of functions should remain stable as long as the variables they enclose don't change.

I believe the work done in <Xwrapper> doesn't need to be based on effects, but to keep things simple on my first contribution I'm just focusing on useXarrow.

Thank you for your time and attention, and for react-xarrows!

Eliav2 commented 1 year ago

This change is accepted.