Git Product home page Git Product logo

eslint-plugin-react-hooks-addons's Introduction

eslint-plugin-react-hooks-addons

ESLint rule to check unused and potentially unnecessary dependencies in React Hooks.

NPM npm downloads

Why?

eslint-plugin-react-hooks is awesome for linting the dependency array of React Hooks. But it doesn't do one thing: unused dependencies in the useEffect or useLayoutEffect hooks are not reported. Unused variables in useEffect's dependency array are perfectly valid in some use cases. However, they might be unnecessary in some other cases which cause the effect hook to run unintentionally.

Take the following code as an example:

const [user1, setUser1] = useState();
const [user2, setUser2] = useState();

useEffect(() => {
  fetch(`someUrl/${user1}`).then(/* ... */);
  fetch(`someUrl/${user2}`).then(/* ... */);
}, [user1, user2]);

Next day you update the code and remove the second fetch but forget to remove user2 from the dependency array:

const [user1, setUser1] = useState();
const [user2, setUser2] = useState();

useEffect(() => {
  fetch(`someUrl/${user1}`).then(/* ... */);
}, [user1, user2]);

Then the useEffect will run whenever user1 or user2 changes, which is probably not your intention. Similar errors occur more frequently when the hook callback function is large and there is a long dependency array. This eslint plugin checks and reports this kind of error.

What if I have a value which is not used in the hook function scope but I want the effect hook to run whenever that value has changed?

You could prepend a /* effect dep */ comment to the value in dependency array then it will be skipped during linting. It brings an addition benefit: the value is explicitly marked as effectful so that other people coming across the code will understand it's not a programmatic error.

useEffect(() => {
  fetch(`someUrl/${user1}`).then(/* ... */);
- }, [user1, user2]);
+ }, [user1, /* effect dep */ user2]);

Install

with npm

npm install -D eslint-plugin-react-hooks-addons

or with Yarn

yarn add -D eslint-plugin-react-hooks-addons

Usage

In your ESLint configuration file:

{
  "plugins": ["react-hooks-addons"],
  "rules": {
    "react-hooks-addons/no-unused-deps": "warn"
  }
}

Explicitly mark a dependency as effectful with /* effect dep */ comment:

useEffect(() => {
  // ...
}, [unusedVar, /* effect dep */ effectVar]);

Then only the unusedVar will be reported as an unused dependency.

Options

effectComment

You can use a different comment to mark dependencies as effectful:

"rules": {
  "react-hooks-addons/no-unused-deps": [
    "warn",
    {
      "effectComment": "effectful"
    }
  ]
}

additionalHooks

The rule checks useEffect and useLayoutEffect hooks by default. It can be configured to check dependencies of custom hooks with the additionalHooks option. This option accepts a pattern key which is a regex pattern. If you set the replace key to true, it would replace the default hooks.

"rules": {
  "react-hooks-addons/no-unused-deps": [
    "warn",
    {
      "additionalHooks": {
        "pattern": "useMyCustomHook|useMyOtherCustomHook",
        "replace": true
      }
    }
  ]
}

Note: this eslint plugin is supposed to work in tandem with eslint-plugin-react-hooks, as it doesn't check things that have already been reported by that plugin.

License

MIT Licensed.

eslint-plugin-react-hooks-addons's People

Contributors

dependabot[bot] avatar szhsin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

zmeyc spoof14

eslint-plugin-react-hooks-addons's Issues

Add a rule for detecting unnecessary stable dependencies

Hey, I like your plugin and it works great. Although I have one addition which would be useful.
Some actions like dispatch actions (from useState) are referred to as stable references. They do not change and thus are not needed as dependencies.
Although it makes no difference if you add it, technically it's just unnecessary code.

A rule to detect this would be nice, for example in the code:

const [loading, setLoading] = useState(true);
const startLoading = useCallback(() => setLoading(true), [setLoading]); // setLoading is not needed because it is a stable reference

According to the react documentation regarding hooks this should apply to the following 3 hooks:

  • useState
  • useReducer
  • useId

https://reactjs.org/docs/hooks-reference.html

[Feature Request] Support for `React.useEffect`, `React.useLayoutEffect` etc,...

Currently The rule applies to useEffect and useLayoutEffect but not React.useEffect and React.useLayoutEffect.

We do use React.* pattern in our codebase so it would be great if the rule supports them. If not default, perhaps as "additionalHooks" -> "pattern" configuration. ("pattern": "React.useEffect" doesn't seem to work?)

Working with React.useMemo

Hello !

I tried the plugin, it works great with useEffect but I'm having trouble making it work with useMemo :

  const testMemo = React.useMemo(() => {
    return Date.now()
  }, [/* effect dep */ forceRefresh]) // <== eslint: unnecessary dependency: 'forceRefresh'

  const testMemo2 = useMemo(() => {
    return Date.now()
  }, [/* effect dep */ forceRefresh]) // <== eslint: unnecessary dependency: 'forceRefresh'

  React.useEffect(() => {
    console.log('hello')
  }, [/* effect dep */ forceRefresh]) // <== ok, no eslint errors

I tried with the following configuration:

    'react-hooks-addons/no-unused-deps': [
      'warn',
      {
        additionalHooks: {
          pattern: 'React\\.useMemo|useMemo',
          replace: false,
        },
      },
    ],

Is this plugin compatible with useMemo ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.