hooks icon indicating copy to clipboard operation
hooks copied to clipboard

useMediaQuery: Cannot read properties of undefined (reading 'removeListener')

Open llemire-exp opened this issue 10 months ago • 1 comments

I'm sorry in advance if this question shouldn`t be asked here, but I am not sure where is the best place for it.

In our app, we use React-bootstrap which uses this library, sometimes, when we clear the cache of the browser and try to navigate to another page we get this error and the whole app crashes:

Image

It originates from the OffCanvas component which uses the useBreakpoint hook which in turn uses the useMediaQuery hook.

The issue comes from the fact that in the cleanup of the useEffect of the useMediaQuery hook, it looks like we assume that mql is never undefined.

https://github.com/react-restart/hooks/blob/961d4320a5227f8e9e848c578d0341aeaa177d45/src/useMediaQuery.ts#L61C3-L86C14

My question is: what could cause mql to be undefined in the cleanup function here is we already check for undefined at line 63? Should there be a simple check in the cleanup so that we return if mql is already undefined?

I have tried to reproduce the issue in a new project with only the bare minimum dependencies, but I have not been able to, I'm posting here to see if anyone has any clue as to how this issue could happen.

Any help is appreciated.

llemire-exp avatar Mar 24 '25 17:03 llemire-exp

I did more investigating and found out that when the hook was created, there was a check for if mql is undefined: link but then in another commit it was removed: link was there a reason why this was removed?

llemire-exp avatar Mar 25 '25 13:03 llemire-exp