reactjs / reactjs/react.dev

Explanation on what can go wrong if Hooks were called inside loops or nested functions?

Open
#2,492 2 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

The Rules of Hooks section states that the first rule of Hooks is to only call hooks at the top level, i.e. "Don’t call Hooks inside loops, conditions, or nested functions". Later in the section, it explains what happens if we put a Hook call inside a condition. This still leaves me with some questions/doubts though. Are there examples where something can go wrong if Hooks were:

  • called inside a loop?
  • called inside a nested function? Furthermore, isn't a custom hook just a nested function? 🤔

I've tried to dig into some related questions on Stack Overflow here and here, but the answers provided only give the correct examples, but not the incorrect ones.

Could you provide incorrect examples for the other two cases? Or at least a little bit clarification would be most appreciated. :)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Rules of Hooks section, especially the existing explanation of conditional Hook calls. Add incorrect examples or clarification covering Hooks in loops and nested functions, including how custom Hooks differ, and consider the work done when these cases are clearly explained in the documentation.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.