How do I configure eslint rules to ignore react-hooks/exhaustive-deps globally?

Viewed 20619

I have a react component with a useEffect hook that looks like this:

const LocationEditor: React.FC<SectionEditorProps> = (props) => {
const [section, setSection] = useState({...(props.section as Location)});
useEffect(() => {
    props.onChange(section);
}, [section]);

I'm getting this warning when I run the project:

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect  react-hooks/exhaustive-deps

So I tried changing the component to look like this, destructuring props:

const LocationEditor: React.FC<SectionEditorProps> = ({section, onClickCancel, onClickSave, onChange}) => {
    const [tmpSection, setSection] = useState({...(section as Location)});
    useEffect(() => {
        onChange(tmpSection);      
    }, [tmpSection]);

If I add this comment before the dependency array, I can make the warning go away:

// eslint-disable-next-line react-hooks/exhaustive-deps

However, when I add the block below to eslintConfig in package.json it doesn't seem to do anything:

{
  "plugins": [
    "react-hooks"
  ],
  "rules": {
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "off"
  }
}

I see some people talking about using the .eslinrc file, but I thought you could also configure rules globally in package.json and I can't find that file in my project.

Is there something I'm missing here?

1 Answers

Usually you don't want to disable the rule. It has been heavily tested and there are very very few cases where it's worthwhile to disable/silence.

Try to figure out if the rule is telling you something worthwhile, in my experience it usually is pointing to a possible bug I didn't notice.

If you're sure the rule is wrong, for example because you're fetching a single time on load and you're sure it never had to execute again, you should disable it with the one-liner you mentioned

// eslint-disable-next-line react-hooks/exhaustive-deps

Definitely don't disable it globally since it won't protect you from potential bugs.

Related