hooks is called conditionally compiling error?

Viewed 3020
  Line 15:3:  React Hook "useEventListener" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?  react-hooks/rules-of-hooks

Search for the keywords to learn more about each error.

Hi when I am trying to run the below code on local I am getting the above error, but online editor compile successfully? why?

https://stackblitz.com/edit/react-8o8dib?file=index.js

import { useCallback } from 'react';
import useEventListener from './useEventListener';

const ESCAPE_KEY = 27;

const useEscape = (callback, disabled = false) => {
  if (disabled) return;

  const handleEscapePress = (event) => {
    if (event.keyCode === ESCAPE_KEY) {
      callback(event);
    }
  };

  useEventListener('keydown', handleEscapePress);
};

export default useEscape;

I am using intellij webstrom.

1 Answers

Issue

You conditionally return early, so the useEventListener isn't called/invoked every render cycle.

Solution

Seems disabled is used to prohibit the callback from firing, so put the condition on that instead.

import useEventListener from './useEventListener';

const ESCAPE_KEY = 27;

const useEscape = (callback, disabled = false) => {
  const handleEscapePress = (event) => {
    if (event.keyCode === ESCAPE_KEY) {
      !disabled && callback(event);
    }
  };

  useEventListener('keydown', handleEscapePress);
};

export default useEscape;
Related