Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

TSLint rule for detecting invalid uses of React Hooks

License

NotificationsYou must be signed in to change notification settings

Gelio/tslint-react-hooks

Repository files navigation

Downloads badgeVersion badgeLicense badgeGitHub stars badgeBuild Status

Demo

A TSLint rule that enforces theRules of Hooks forReact hooks.

The rule is based on anESLint plugin for react hooks.

Features

  • detects using React hooks inside potentially-conditional branches:
    • if statements
    • short-circuit conditional expressions (&&,||)
    • ternary expressions
    • loops (while,for,do ... while)
    • functions that themselves are not custom hooks or components
  • detects using React hooks in spite of an early return
  • support for detecting hooks from namespaces other thanReact (e.g.MyHooks.useHook) (optional)

Installation

First, installthe rule:

npm install tslint-react-hooks --save-dev

Then, enable the rule by modifyingtslint.json:

{"extends":[// your other plugins..."tslint-react-hooks"],"rules":{// your other rules..."react-hooks-nesting":"error"}}

To use report rule violations as warnings intead of errors, set it to"warning".

Options

While the rule works fine out-of-the-box, it can be customized. To specify options, use thefollowing syntax when modifyingtslint.json:

{"extends":[// your other plugins..."tslint-react-hooks"],"rules":{// your other rules..."react-hooks-nesting":{"severity":"error",// "error", "warning", "default" or "off""options":{// options go here}}}}

Available options

  • "detect-hooks-from-non-react-namespace" - when set totrue, violations will be also reportedhooks accessed from sources other than theReact namespace (e.g.MyHooks.useHook will betreated as a hook).

    By default, only direct calls (e.g.useHook) or calls fromReact namespace (e.g.React.useState) are treated as hooks.

Have an idea for an option?Create a new issue.

Workarounds

For some arrow functions/function expressions, the rule has no way to determine whether those are acomponent, a hook, both of which could contain hook calls, or a regular function that should notcontain hook calls.

constwithHoc=<TPropsextendsobject>(Component:ComponentType<TProps>)=>(props:TProps,)=>{const[state]=useState();return<Component{...props}/>;};

The workaround in those cases is to use anamed function expression:

constwithHoc=<TPropsextendsobject>(Component:ComponentType<TProps>)=>functionWrappedComponent(props:TProps){const[state]=useState();return<Component{...props}/>;};

Naming the function like a component (inPascalCase) unambiguously lets the rule treat thefunction as a component.

False positives and not-covered cases

There are some cases that seem hard to analyze and may result in false positives or false negatives.

In such cases, disable the rule for a specific line using the following comment:

// tslint:disable:react-hooks-nestinguseEffect(()=>{});

Looping over static arrays

The rule may report false positives, for example in:

functionMyComponent(){constarray=[1,2,3];array.forEach(value=>{React.useEffect(()=>console.log(value));~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~[Ahookcannotbeusedinsideofanotherfunction]});}

TheuseEffect hook will be called unconditionally and the call-order will be the same betweenrenders.

Using renamed hooks (that do not start withuse)

The rule only treats functions that start withuse as hooks. Therefore, renaming the hook willresult in avoiding the rule:

constrenamedUseState=React.useState;functionMyComponent(){const[state,setState]=renamedUseState(0);}

Unconditional nesting

Unconditional nesting, for example:

functionMyComponent(){if(true){constvariableThatCannotBeLeaked=useContext(SomeContext);useEffect(()=>{console.log(variableThatCannotBeLeaked);});}return<div>Text</div>;}

is treated as conditional nesting. It seems hard to verify if the condition is in fact a constant,therefore such a situation will always result in a rule violation.

In situations where such anif statement was used to create an additional block scope, use theblock scope directly:

functionMyComponent(){{constvariableThatCannotBeLeaked=useContext(SomeContext);useEffect(()=>{console.log(variableThatCannotBeLeaked);});}return<div>Text</div>;}

Development

After pulling the repository, make sure to run

npm install

The source code for the rule is located in thesrc directory.

For more information about the developing custom TSLint rules, take a look atTSLint's documentation.

Testing the rule

Run

npm runtest

to compile the rule and run automatic TSLint tests.

They are located in thetest directory.

Author

The author of this rule is Grzegorz Rozdzialik.

About

TSLint rule for detecting invalid uses of React Hooks

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors3

  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp