简体   繁体   English

每次调用反应钩子时都会添加一个事件侦听器吗?

[英]Does a react hook add an event listener every time it's called?

Let's say I have a react hook that listens to an event like resize on the window object.假设我有一个反应钩子,它监听window object 上的resize之类的事件。

I want to know if every time I use the hook in some components all over the application I'm also adding a different event listener on window .我想知道每次我在整个应用程序的某些组件中使用钩子时,我还会在window上添加不同的事件侦听器。

If the answer is yes, then i suppose this will be bad for performances, how can i avoid it?如果答案是肯定的,那么我想这对表演不利,我该如何避免呢?

Here's an example of the hook i want to implement:这是我要实现的钩子的示例:

export const useMediaQuery = (): ReturnObject => {
  const [desktop, setDesktop] = useState(false);
  const getViewport = (): void => {
    setDesktop(window.matchMedia(desktopQuery).matches);
  };

  useEffect(() => {
    getViewport();
    const listener = (): void => getViewport();
    window.addEventListener('resize', listener);
    return (): void => window.removeEventListener('resize', listener);
  }, []);

  return {
    deviceType: desktop ? DeviceType.Desktop : DeviceType.Mobile,
  };
};

when you use custom hooks , React will allocate a new piece of memory for that component to use that custom hook.当你使用自定义 hooks时,React 将为该组件分配一块新的 memory 以使用该自定义 hook。

so, I think the answer is YES所以,我认为答案是肯定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何正确地将事件侦听器添加到 React useEffect 挂钩? - How to correctly add event listener to React useEffect hook? 使用react hooks,你将如何编写一个依赖于state的事件监听器,而不需要在每次state变化时添加和删除? - Using react hooks, how would you write an event listener dependent on state that does not need to be added and removed every time the state changes? 在事件监听器中反应挂钩保存状态错误? - React hook saved state in Event Listener wrong? 从滚动事件侦听器反应 setState 钩子 - React setState hook from scroll event listener React useEffect 钩子事件监听器触发了两次 - React useEffect hook event listener fired twice 反应添加/删除事件监听器 - React add/remove event listener 如何在 React 中添加事件监听器? - How to add event listener in React? 为什么在 react 中使用 useEffect 挂钩时,对事件侦听器的回调会按预期工作? - Why does callback to the event listener work as intended while using the useEffect hook in react? 将事件侦听器添加到具有给定属性的每个组件 - Add event listener to every Component with a given property 在我的React自定义挂钩的每次调用中添加和删除事件侦听器是否太昂贵? 怎么避免呢? - Is it too expensive to add and remove event listeners on every call of my React custom hook? How to avoid it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM