eBay / nice-modal-react

A modal state manager for React.
https://ebay.github.io/nice-modal-react
MIT License
2.04k stars 118 forks source link

returned functions of useModal hook have "unstable" identity #53

Closed janczizikow closed 2 years ago

janczizikow commented 2 years ago

First of thanks a lot for a cool library 😁

I found that function identity of "handlers" returned from useModal hook isn't stable. It changes on some renders making it a bit hard to reliably use with other hooks. For example:

const [counter, setCounter] = React.useState(0);
const userModal = useModal(UserInfoModal);
const { show } = userModal;

React.useEffect(() => {
  if (counter >= 2) {
    show();
  }
}, [counter, show]) // <- once `counter` reaches 2 the component will continue to infinitely re-render

I think it would be a nice improvement to memoize the handlers in a way that they wouldn't change depending on the state - right now calling show() will change the identity of show 🤔 A small demo showcasing the issue: https://codesandbox.io/s/nice-modal-lqj0kg?file=/src/UserList.tsx

janczizikow commented 2 years ago

I was investigating this further and created a PR for this. The fix seems pretty simple 🙂