The last couple of months have been anything but ordinary in the React ecosystem. It all started at the React Conf 2018, where React development team announced a new feature, which they named React Hooks. If this feature gets accepted by the community, it is going to be a huge breakthrough and it is going to change the way developers perceive and write React components. Having that in mind, letâ€™s talk about React hooks and what they are bringing to the React community.
What are React hooks?
- ONLY CALL HOOKS AT THE TOP LEVEL! â€“ which means you should only use hooks in your top-level function, and not in any kind of conditions, loops or any nested functions.
- ONLY CALL HOOKS FROM REACT FUNCTIONS! â€“ which means you are only allowed to use the hooks in React component functions and custom hooks.
But what makes React hooks so special? We could already use state, lifecycle methods, context etc., long before hooks. So why would we need them?
Why React hooks?
React hooks are meant to change the way we write React components. As we all know, there are two kinds of components in React:
- stateful (also called smart components or containers), which always had to be class-based components, because state, lifecycle methods and couple of other methods were only available in class-based components;
- stateless (also called pure, dumb or presentational components), which could either be class-based or functional components;
Here we have a simple class-based component in React. In a real world application, you would have tens or hundreds of them, and some would be much bigger and much more complex than this. The component needs to have a local state, so it must be class-based. Or, so it was, until React 16.8 and the introduction of hooks.
Above we have the same component like before, with the same behavior, but this time it is written as functional component, with the help of React hooks. The difference is that the function component is much more compact, has less lines (51 compared to 72, and the difference is pronounced even more on larger components), and also we are not using â€śthisâ€ť (which is a big benefit by itself).
If you want to learn more about React hooks, you can start by reading the official React documentation here: https://reactjs.org/docs/hooks-intro.html.