What are Hooks in React anyway?

  • Hooks let you use React features without writing a class.
  • Hooks are functions that let you “hook into” React state and lifecycle features from function components.
  • Hooks allow you to reuse stateful logic without changing your component hierarchy.
  • Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data).
  • Hooks work side-by-side with existing code so you can adopt them gradually.

You can read more in-depth information in the official documentation, Hooks Intro

Hook Rules

Only Call Hooks at the Top Level

Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Only Call Hooks from React Functions

Don't call Hooks from regular JavaScript functions. Instead, you can:

  • Call Hooks from React function components.
  • Call Hooks from custom Hooks

By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.

Hooks cannot be conditional

Every Hook is initially added into a list that is reviewed on every render cycle. So if the Hooks don't add up, there is something amiss and any linter set up correctly will warn you.