Rules of using Hooks in React
Hooks are a new addition in React v16.8.0. They are special functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes, they let you use React without writing a class.
With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.
1. 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.
❌️ Don’t use a Hook inside a condition like this:
️✅Instead, we should put that condition inside our Hook:
React relies on the order in which Hooks are called. if we put a Hook call inside a condition, the name !== ' ' condition is ‘true’ on the first render, so we are able to run this Hook.
However, on the next render the user might clear the form, making the condition ‘false’. Now that we skip this Hook during rendering, every next Hook call after the one we skipped would also shift by one, leading to bugs.
You can read more details in depth here
2. Only Call Hooks from React Functions
✅ Call Hooks from React function components.
✅ Call Hooks from custom Hooks
Function components in React look like this:
Or like this:
However, you don’t need to worry about this problem if you use the provided ESLint Plugin.
React provides an ESLint plugin called:
To enforce these two rules automatically and avoid bugs. You can add this plugin to your project if you would like to try it.
This plugin is included by default in ‘Create React App’
Note: React v16.8.0 is the first release to support Hooks. When upgrading, don’t forget to update all React packages, including React DOM.
React Native supports Hooks since the v0.59 release: React Native
Do we need to rewrite all existing Class components to Hooks?
The answer is No, we don’t need to do that. There are no plans to remove classes from React . But you should start trying Hooks with Function components in your new code.
We can continue to use libraries such as Redux and React Router:
- React Redux since v7.1.0 supports Hooks API and exposes hooks like ‘useDispatch’ or ‘useSelector’.
- React Router supports hooks since v5.1.
Other libraries might support hooks in the future too.
You can read the frequently asked questions about Hooks here: Hooks FAQ