Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: react-hooks/rules-of-hooks does not support do/while loops #28713

Open
tyxla opened this issue Apr 2, 2024 · 3 comments · May be fixed by #28714
Open

Bug: react-hooks/rules-of-hooks does not support do/while loops #28713

tyxla opened this issue Apr 2, 2024 · 3 comments · May be fixed by #28714
Labels
Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug

Comments

@tyxla
Copy link

tyxla commented Apr 2, 2024

React version: 18.2.0

Steps To Reproduce

  1. Use a hook inside a do/while loop.

  2. You'll see that it's not considered a violation of the rule.

Code example:

function ComponentWithHookInsideDoWhile() {
	do {
		useHookInsideLoop();
	} while (true);
}

The current behavior

The react-hooks/rules-of-hooks does not consider hook usage inside a do/while loop a violation.

The expected behavior

I expected that I'd see the following ESLint error:

React Hook useHookInsideLoop() may be executed more than once. 
Possibly because it is called in a loop. 
React Hooks must be called in the exact same order in every component render.
@tyxla tyxla added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Apr 2, 2024
@tyxla
Copy link
Author

tyxla commented Apr 2, 2024

I've worked on fixing this in #28714

@pranshu05
Copy link

Maybe instead of using do while loop you can do conditional rendering, create a state of condition and render the hook based on the condition.

In this method the hook won't be executed more than once!

@tyxla
Copy link
Author

tyxla commented Apr 27, 2024

@pranshu05 this issue isn't about how to write conditional or loop hooks in React. This is about the ESLint rule that catches whether someone is using a hook potentially in a loop. There's no guaranteed way through static code analysis to catch if a loop will iterate more than once or not. Also, the rules of hooks ESLint rule already warns if someone is using a hook in a while, which can also have one, or even zero iterations. So it only makes sense that we do the same for do/while which will have 1 or more iterations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants