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.
Note: Hooks solve More problems, but for now we will focus on the below-mentioned ones -
There are two rules that you need to follow while using React Hooks:
For more details on the rules check — https://reactjs.org/docs/hooks-rules.html#explanation
React core team has provided us with a lint rule that helps us use the hooks properly (enforce the above-mentioned rules). You can also add the same in your ESLint configuration.
Add the ESLint rule by doing npm install -D eslint-plugin-react-hooks and add this to ESLint configuration:
{
"rules": {
…,
"react-hooks/rules-of-hooks": "error"
},
"plugins": [
…,
"react-hooks"
],
}
In the upcoming stories, we will cover the below-mentioned hooks in order: