This is a basic explanation of the React Hooks, so there won't be any code at all. The context in this text is for someone who has a basic knowledge in React. There will be a part two on how to use predefined Hooks in the future.
React Hooks are probably the most important release from last year in React, because of how they are changing the way React was done before. React Hooks are basically functions that give extra complexity to Functional Components that can now a state logic, as well as something similar to the Lifecycle of a Class Component.
They let you “Hook” into the React State with the “useState” hook, being very similar to its alternative “this.setState” except it will not merge the old and new states.
For managing the Lifecycle in Functional Components, the Effect Hook will be in charge. This is a very complex hook, and will need an article by itself to fully explain it, but in summary, it can perform similar to componentDidMount, componentDidUpdate, and componentWillUnmount. The magic is that everything is done with one single API.
There are also “Custom Hooks” where people can create them and share them, to increase the functionality and reusability.
Some great custom hooks: https://github.com/rehooks/awesome-react-hooks
Quoting the official Documentation:
“There are no plans to remove classes from React… We intend for Hooks to cover all existing use cases for classes, but we will keep supporting class components for the foreseeable future.”
That being said, Hooks are starting to get the same functionality as React Classes, while being lighter, more configurable, less complex, and more reusable.
Our advice in steps:
1. Get comfortable with Classes
2. Start to use “dumb” Functional Components
3. Differentiate when to use each one
4. Do not try to Refactor the old code to Hooks, but create new Functional Components with Hooks (the official Documentation also recommends this)
1. Inside a loop, a condition or a nested function.
2. Inside Class Component (obviously)
Hooks are the new trend in the React world. They will not replace Classes, but the idea is to use them more and more, because of its simplicity yet added functionality. Use them as much as possible, and try the Custom Hooks, since there is probably somebody who struggled with a problem and uploaded the solution as a React Hook.