What you should know about React Hooks, before using them.
At the start of 2019 and as expected, the new React version 16.8.0 ships with the new stable implementation of React Hooks.
These hooks will be a game-changer for the React Community, before starting to use React Hooks, we should ask some very useful questions that will help us to understand well this new feature.
First thing first, why React Team add this feature? what is the problem that React Hooks will solve? Why hooks and no other things?
Yes, this is what we should ask first, usually, everybody gets excited about new things and starts using them without understanding the reasons behind their existence.
Since not all new things are good for your projects, and your team …, these questions will help you be confident in your choices (when to use and how), and able to critique and clearly express your thoughts on them.
Let’s start by why? Why we might need to use React Hooks?
The main challenge we have when developing our React application is how to make the logic of some huge components reusable to share it between components and avoid duplication, which leads us to use design patterns that solve this problem, like HOC (high order component), render prop, drill prop, or mixins, all of which can lead to complex code that is difficult to write, improve, maintain, and test.
These design patterns are the most used to overcome this kind of challenge, but absolutely with a cost, since every solution has its cost, these approaches came with a complex mechanism to think about, an implicit method of implementation that makes the code hard to understand and co-locate.
React hooks give us the capability to use only functional components for all our needs over the class components to avoid using these patterns.
The functional components are easier to read and test with less code before hooks a functional component had a limitation since it didn’t have its local state and lifecycle methods, but now with React Hooks, it becomes possible to have a local state and lifecycle methods, and finally stop thinking about the frightening ‘this’ keyword.
I recommend and encourage you to read these articles, so you can see the benefits of functional components:
Functional vs Class-Components in React
React stateless functional components nine wins you might have
React Hooks improve the development experience by using composition instead of inheritance by relying on functions, not classes, they bring the missing piece of React, sharing logic between functional components, in a sophisticated way, Hooks make the need for the patterns like prop drilling, render props, and HOCs for the most cases unnecessary.
And as Sophie Alpert said in React Conf 2018:
- It’s hard to reuse stateful logic between components
- Complex components become hard to understand
- Classes confuse both people and machines
React hooks come to solve these nowadays problems:
- Wrapper hell (caused by design patterns: HOC, render prop, drilling prop)
- Huge components (that are hard to test and maintain, hard to co-locate code)
- Confusing classes (this keyword, hard to make it reusable)
Since the problems mentioned above are related to each other, we can’t solve them in isolation.
React hooks brings a new API that hits these three issues with 10 stones at a time so we can make sure they’re dead :).
In the longer term, we expect Hooks to be the primary way people write React components — React Doc
If hooks are going to be that important, why not learn about them now?
So what is React Hooks? What are these about?
They are collectively called hooks, they are special functions that add state, effect feature, performance optimization, and more to your functional components.
There are 10 built-in functions that have their unique name all beginning with a three-letter ‘use’, but with different functionality and use cases, they are completely optional you don’t have to re-write your existing class but you can start using them in the new ones since react is all about incremental adoption.
React Hooks are just functions that take an argument and return value, in addition too, you can create your own ones easily as a custom hook.
If you wondering how these hooks work under the hoods I suggest to you these articles:
React hooks: not magic, just arrays
Under the hood of React’s hooks system
Before using and seeing them in practice we have to be aware of the rules of using these hooks.
We have to respect these rules otherwise we will get confusion and unexpected results, since React relies on the order in which Hooks are called, the order of the Hook calls must be the same on every render.
React won’t natively throw errors or warnings to let you know, you have to add a linter plugin that ensures and enforces these rules automatically within your projects.
There are only two rules to follow.
1. Only Call Hooks at the Top Level i.e. not within conditionals, loops, or nested functions.
2. Only Call Hooks from React Functions i.e. Functional Components and Custom Hooks.
Now let’s see them one by one starting with the one you will use the most:
- useState: This hook gives us the ability to make functional components have their local state through a very simple API as you can see in the example below.
- useReducer: This hook gives us an easy way to organize our state management, if you are already familiar with Redux you will find this easy to understand and work with.
- useEffect: This hook has been made for side effects, it does the same as the class lifecycle methods and more, with a different mental model which matches how the functional component is rendered.
- useContext: This gives us the ability to pass data, config data in our app, and down the components tree without using prop drilling or a third-party library like redux.
- useCallback: Gives us a nice performance gain by memorizing the given callback and updating it when the given dependencies change.
- useMemo: This hook caches some data, saving some computing time on our app and hopefully making it more responsive in the process.
See the other hooks here.
Pros vs Cons
Now it’s time to see the pros and cons of these React hooks.
Pros:
- A better alternative to some common design patterns.
- Easy to test and maintain (functional components).
- Create reusable, isolated components to avoid redundant logic.
- Easy to use and co-locate.
Cons:
- Have to respect its rules, without a linter plugin it is difficult to know which rule has been broken.
- Need considerable time practicing to use them properly (Exp: useEffect).
- Be aware of the wrong use (Exp: useCallback, useMemo). You can read this article by kentcdodds
If we put the pros and cons in the balance, the advantages will gain, because the weight of the problems that the hooks solve are very heavy, and its disadvantages are easy to tackle and avoid.
Conclusion
To recap what we have learned, React Hooks came to solve a very common problem that everyone uses React that they have, they encourage the use of functional components to benefit from its simplicity and efficiency for a scalable, maintainable, and testable codebase.
Since everything has its cons, react hooks also have their own, and we have to be aware of, and respect react team recommendations to avoid unexpected behaviors.
Note that:
“The main motivation is being able to extract and reuse logic between components without introducing extra nesting into the tree.
The fact that this design also eliminates the need for class gotchas is a consequence, not the main motivation. ” — Dan Abramov
“With hooks we separate code not based on the lifecycle method name but based on what the code is doing” — Dan Abramov
Please do not hesitate to give us your thoughts about React Hooks.
Sources:
https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889
https://www.richardkotze.com/coding/hoc-vs-render-props-react
https://reactjs.org/docs/higher-order-components.html
https://reactjs.org/docs/render-props.html
https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889
https://medium.com/@Zwenza/functional-vs-class-components-in-react-231e3fbd7108