Understanding advantages of React Hooks. | Reduce your code to an extent in React.js and React Native.

Mayank Vamja
mayankvamja
Published in
2 min readNov 5, 2020

What are hooks?
React hooks provides a way to use every react features available in react without writing a class. {get rid of this keyword and this binding :)}

So, why using hooks?
By using react hooks, you can reduce as well optimize your code a lot especially when you are using libraries like react-navigation, redux, mobx, etc…

Comparing features in react with class and functional components:

1. useState() : this.state

useState returns a pair of state and function to update state. It has optional argument which is initial value of that state.
As you can see below you can simple get rid of ‘this’ and binding ‘this’ which becomes headache many times. And code is also reduced and more understandable.

2. useEffect : React class lifecycles

The Effect Hook lets you perform side effects in function components. It has two arguments: first is void function, and second is dependency array.
It provides a way to perform many react lifecycles.

Note: Avoiding second argument(array) in useEffect will force execution on every render which can be very dangerous.

// Do not do this (avoid)
useEffect(() => { ... });

Below here is implementation of componentDidMount & componentDidUpdate lifecycles.

Just Think for a minute think how other lifecycles of react component can be implemented in functional component.

componentWillUnmount is usefull when you want your dependencies and initialization destroyed on component unmounted. It can be implemented by returning function as useEffect’s function.

useEffect(() => () => {
console.log("Component will unmount.")
}, []) // empty array.

shouldComponentUpdate is really important React class component feature which allows to decide whether or not to re-render component when state or props are updated. To achieve this in functional component there are two ways:

React.memo() // Recommended for comparing props
useMemo() hook

# React.memo():
React.memo() has two arguments one is child component on which you want to decide whether or not it should update and other optional argument is function which compare old and current props:
Example:

3. useMemo : shouldComponentUpdate

useMemo hook is similar to React.memo but with limited in terms of props comparison which can be done in React.memo.
The useMemo Hook lets you cache calculations between multiple renders by “remembering” the previous computation.

You can learn about all React hooks api here.

React hooks are also implemented in almost all standard libraries like React-router-hooks, React-redux-hooks.

TLDR: There is no need to change your current code from classes to functional components with hooks. It is just how hooks can help in your new and old projects by avoiding classes.

--

--

Mayank Vamja
mayankvamja

Computer Engineer who loves front end development.