Open In App

Rules for using hooks in React

Last Updated : 04 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Using hooks in React follows several rules and guidelines to ensure proper functionality and maintain code quality:

  • Hooks should only be used at the top level of functional components: Hooks should not be called conditionally or within nested functions, loops, or other JavaScript constructs. They should always be called at the top level of a functional component or within custom hooks.
  • Hooks should not be called in regular JavaScript functions or class components: Hooks are meant to be used in functional components and custom hooks. They should not be called in regular JavaScript functions or class components.
  • Hooks should always be called in the same order: The order in which hooks are called within a functional component should always remain consistent across renders. React relies on the order of hook calls to properly associate stateful logic with components.
  • Hooks should only be called from React function components or custom hooks: Hooks should not be called from regular JavaScript functions, event handlers, or other non-React contexts.
  • Hooks should be named with a “use” prefix: By convention, custom hooks should be named with a “use” prefix to indicate that they are hooks. This helps distinguish them from regular functions and makes it clear that they follow the rules of hooks.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads