45

Understanding hooks in React

 5 years ago
source link: https://www.tuicool.com/articles/hit/7JvUZrJ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

React is the most powerful UI library. The team is improving performance and the development experience every day by adding amazing features, which ultimately help developers build amazing apps.

If you scrolled twitter last few days, probably you saw most react developers are celebrating the introduction of the awesome feature called Hooks.

Hooksis the new feature which is still in alpha and would be the official part of React 16.7 very soon.

Tip: Just like other React components, Hooks can be shared and reused between projects using Bit ( GitHub ). You can share hooks into a collection, so they can be discovered, used and synced in any project. Feel free to try.

The problems with React class components

Currently, there are a few problems with the way we write react components. Let’s try to summaries a few common problems.

1) Huge components

We start with a short and simple component. Slowly it grows with complicated logics spread around the constructor, methods and within the lifecycle methods. 

E.g data fetching happens in componentDidMount and at the same time the subscription and registry of event listeners will also reside in componentDidMount , the canceling subscription and cleaning have to be written in componentDidUnmount . All these together make the component huge and difficult to maintain.

2) No states in functional components

The simplest form of the component is a functional component. The real problem comes into the picture when we want to use React features like states, context, refs or lifecycle methods, then we have to convert these functional components into class components.

Hooks enable the functional components to use states and other React features without using class. That means now you need not create classes for a component.

3) Confusing classes

In Javascript, classes are really complicated to work with. If you are not aware of why Javascript class is bad, please spare some time to try to understand how this works and what exactly prototypal inheritance is. 

The reason humans do not like is that Javascript’s this works a lot different than any other language’s this . If anyone misuses this , it will lead to many bugs which are hard to debug and fix.

All these problems potentially make the component prone to the introduction of bugs, whenever we update the code or extract components to make it smaller and reusable.

Read the post How to Use Classes and Sleep at Night by Dan Abramov .

What are Hooks?

Hooks are the new feature which enables the functional component to use features like state, context, lifecycle methods, ref, etc. without writing the class component. Hooks provide the functions like useState to use states.

Let’s first write a simple component in class and then we will rewrite the same using Hooks.

The following counter component has two buttons.

On clicking the first button it increments the number by one and on clicking the second button it decrements the same number by one.

Let’s rewrite the same component using useState Hook:

Explanation:

line 3: const [count, setCount] = useState(0)
is a Hook that lets you use the local states without declaring a class. This method takes one argument as the initial value in the local state. In our case, we wanted to start the value of count from 0. 

The default state value is equivalent to what we do in the constructor this.state . The initial parameter in the useState method can also be an object if needed.

The setCount gets a method from useState to change the value of count in future. 

E.g in line 7 we are passing the new value of count to update its value.

Please note by only using state hook we reduced the number of line of code almost by half.

Square bracket when calling useState

The square bracket is array destructuring. The method useState returns two sets of items. 

The first item is the current value in the state and the second item is a function that lets us change the value.

The above is equivalent to the following:

If you needed more that one state variables that can be done by calling useState multiple times. Each instance will update independently.

The useState hook covers the legacy use case of the constructor, this.state and the setState functionalities.

useEffect Hook

This hook lets us perform the side effect, hence useEffect is the name of this hook. In React calling the API to fetch data, subscribing to event listeners, updating DOM and integrating third-party libraries like Highcharts or D3 to update DOM are some example of side effects.

The API calls, changes to the DOM and other side effects all are done in the component lifecycle componentDidMount and componentDidUpdate .

This hook is a combination of these lifecycle methods. To know more about react component lifecycle methods, please refer tothis blog post.

Let’s add more features in the above counter example. We will update the DOM by changing the title of the window. We will use the document.title from browser API.

Please note, in line 12 and line 15 there is the duplication of same code which has to be done as per the component lifecycle methods. One time after mounting is done and rest all the time for state updates in componentDidUpdate .

Let’s rewrite the above using useEffect hook.

The useEffect hook combined the functionality of componentDidMount and componentDidUpdate . This method takes at-least one function as a parameter and returns nothing.

The useEffect should be written inside the component so that it can use the variable from useState and remain within the scope.

The above is a very short example of DOM manipulation. There could be more logics living together in these methods and mostly you will have to write in two methods.

E.g. if you are using Highcharts library, the following is sample setup and same you have to add in componentDidUpdate to update the chart.

Sometimes when the component is going to unmount we need to clear stuff like subscriptions, event listeners and clear other objects to avoid memory leaks. In classic React component, all these things were done in componentWillUnmount.

Let’s add some subscription and clear those while unmounting of the class component.

This is one basic example of how componentDidMount, componentDidUpdate and componentWillUnmount work together.

Let’s rewrite the above using hook.

Please note that now the useEffect has a return function. This return function is optional and gets called when the component is unmounted.

Isn’t it super cool that react effect hook somehow managed to combine the functionalities of few lifecycle methods? There are a few other ways to add conditions to optimize the effect hook, you can find it here in detail.

Other hooks

There are few other hooks available like useContext to access the context API, useRef to access the ref API, useReducer which is similar to redux reducer where actions can be dispatched state can be changed. There are few other APIs to know more, please refer to this link .

You can also create your custom hooks to extend the functionality.

Benefits

  • Share-ability
    In hooks, all we do is pass function or return functions. Which directly means that those can be extracted in separate methods and can be shared with other components. This enables us to share logics across the functional and class components.
  • Short and simple components

    In the above code example, we saw how drastically the hooks reduced the number of methods and number line of code. We need to write less using hooks.
    In class components, we need to access state variables by this.state.someValue and in hooks, we can directly use someValue , which makes it cleaner.

Are the class components going to be deprecated?

No, the class components and hooks will live together for a much longer time. If react team deprecates the class component every one has to refactor the existing classes to hooks, which will break the current apps.

Whether to use Hooks or not?

Although the hooks are still in alpha version, definitely it is going to be the future as it gives some amazing benefits. You should play around with it and get ready for its release.

Conclusion

That was it on this introduction of react hooks. Hope you find this useful. Please share your thoughts about hooks in the comment section, I’d be happy to talk!If you liked this post, please share, comment and give few :clap: :blush: Cheers


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK