Note: This is the first article in a series of articles where we will cover React Hooks in Depth and try to understand their usage.
React Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. It is a fundamental shift on how you’ll approach writing React.
Hooks do not have any breaking changes and are 100 % backward compatible. If you are a newbie learning react or seasoned pro try this!
But what is a Hook?
Hooks are functions that let you “hook into” React state and life-cycle features from function components. Hooks don’t work inside classes — they let you use React without classes. You can definitely mix classes and function components with Hooks in a single tree.
At React Conference 2018, Sophie Alpert and Dan Abramov introduced Hooks, you can watch the video introduction below:
React core team recommends Hooks in new components you write. In the longer term, they expect Hooks to be the primary way people write React components. So, use hooks in functional components of your new project and new components of your existing project.
The Problems Hooks Solve
Note: Hooks solve More problems, but for now we will focus on the below-mentioned ones -
Functional Components can use State like class based components
We can avoid writing almost the same thing in componentDidMount() and componentDidUpdate()
Achieve the same functionality by writing less and much cleaner code
Rules of React Hooks
There are two rules that you need to follow while using React Hooks:
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. 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.