Gelio / tslint-react-hooks

TSLint rule for detecting invalid uses of React Hooks
MIT License
218 stars 10 forks source link

Fix detecting hooks uses after early return #10

Closed Gelio closed 5 years ago

Gelio commented 5 years ago

This PR adds reporting rule violations whenever a hook appears after a return statement.

This should fix #1.

After this PR gets merged to develop, I will release a 2.0.0-alpha.1 version of the rule for developers to verify that it works and has no bugs. After a few days, I am going to release a 2.0.0 version of the rule.

How this feature works?

Whenever a return statement is encountered, the parent function/method is found and stored in a set of functions that have a return statement.

https://github.com/Gelio/tslint-react-hooks/blob/c545a51c467bbceb1b2d366f791226f924048cb5/src/react-hooks-nesting-walker/react-hooks-nesting-walker.ts#L39-L47

Upon encountering a hook call, the parent function is found. If it already contains a return statement, a rule violation is reported (because the parent function - a hook or a component - may return early):

https://github.com/Gelio/tslint-react-hooks/blob/c545a51c467bbceb1b2d366f791226f924048cb5/src/react-hooks-nesting-walker/react-hooks-nesting-walker.ts#L97-L99

I am not proud of how the code is structured right now. The lengthy visitHookAncestor method hurts my eyes the most. I have an idea on how to refactor it, but first I would like to get early hooks detection out of the way.