Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 351
master_chef Avatar asked Jan 13 '21 15:01

master_chef


1 Answers

Opinion #1:

Don't disable. That rule has been tested and re-tested and is battle scarred and probed as much if not more than any other ESLint rule.

I too, thought I knew better. But none of us do. Don't disable it, trust me, it knows better than you and me. I've been there too.

Just do what the rule says, and if it breaks your app be glad because it found a bug for you for free and you should fix it instead of forcing your app to work.

Option #2:

"Just do what the rule says" - it's not always the best option. An example: if you need to fetch data from a server, you usually pass to useEffect an empty array as a second argument (because you need to run the callback only once when your component did mount) - and it's an official advice from React documentation. And then "exhaustive-deps" often starts to annoy you with warnings that you "forgot" dependencies (but you're sure you didn't). And adding dependencies you don't need is an antipattern, because it may lead to unnecessary rerenderings or even to an infinite cycle of rerenderings...

like image 170
Obed Parlapiano Avatar answered Sep 18 '22 04:09

Obed Parlapiano