Replacing React Lifecycle Methods with Hooks: A Comprehensive Guide

栏目: IT技术 · 发布时间: 6年前

内容简介:Using Hooks to replace componentDidMount, componentWillUnmount, componentWillReceiveProps, componentDidUpdate.Class components are verbose and cumbersome. In many cases, we are forced to duplicate our logic in different lifecycle methods to implement an ‘e

Using Hooks to replace componentDidMount, componentWillUnmount, componentWillReceiveProps, componentDidUpdate.

May 4 ·4min read

Replacing React Lifecycle Methods with Hooks: A Comprehensive Guide

Why Hooks? / Why not Classes?

Class components are verbose and cumbersome. In many cases, we are forced to duplicate our logic in different lifecycle methods to implement an ‘effect logic’.

Class components do not offer an elegant solution to sharing logic between components (HOC and friends are not an elegant solution) — React Hooks, on the other hand, give us the ability to build custom hooks, a much simpler solution.

And the topping of the cake — we’ve had enough dealing with this .

Sharing Components: Classes vs Functions

We share and reuse components with our team through cloud component hubs like Bit.dev . The logic of that is pretty simple: we maximize code reuse, keep a consistent UI and collaborate across repositories.

To make the most out of tools like Bit.dev and guarantee we make it easy and simple to reuse and maintain other’s components, it’s best to go for function components with hooks. They’re simply more ‘lightweight’, elegant, and easy to understand. They are, IMHO, what components should have been all along.

Replacing React Lifecycle Methods with Hooks: A Comprehensive Guide
Published and documented React components on Bit.dev

componentDidMount

componentDidMount 's equivalent in function components is the useEffect hook with an empty array as its second argument.

For instance, we can use componentDidMount to load some data on component load as follows:

(The component is at https://bit.dev/jauyeunggithub/componentdidmount )

We loaded some data from an API with the componentDidMount hook, which is rendered in the render method.

To do the same thing with the useEffect hook in function components, we write:

We have the fetchData function to get the data.

Then we call it in the useEffect callback.

We passed in an empty array to useEffect as the 2nd argument so that the callback only runs on component's first load.

We can’t have async functions as a callback. Otherwise, we’ll get an error.

componentWillUnmount

componentWillUnmount is a lifecycle method for class-based components that's loaded when the component is being removed from React virtual DOM.

We can run some code when the component unmounts by writing:

We call clearInterval to remove the timer in the componentWillUnmount hook so that we remove the timer when the component unmounts.

To do the same thing with hooks, we can use the useEffect hook again.

We return a callback that runs code before the component unloads.

To function component of the example above is:

We have the date and timer states to hold the current date and the timer object respectively.

The timer is created by setInterval when the component loads as indicated by the empty array in the 2nd argument of useEffect .

In the callback, we passed into useEffect , we return a function that runs cleanup code.

Therefore, we have clearInterval in that function to remove the timer from when the component unmounts.

componentWillReceiveProps / componentDidUpdate

The useEffect hook is also the equivalent of the componentWillReceiveProps or componentDidUpdate hooks.

All we have to do is to pass in an array with the value that we want to watch for changes.

For instance, the following code has a SuperCounter component with the componentDidUpdate hook:

componentDidUpdate takes a prevProps parameter.

We check if this.props.count is different from prevProps.count .

If it is, then we update the superCount state with this.props.count * 2 .

We can write the hooks equivalent as follows:

We also have a SuperCounter component that has the destructed count prop in the parameter.

Then in the useEffect hook, we called setSuperCount in the callback.

The 2nd argument is an array with the count variable.

This means that we’re watching for changes in the value of the count variable.

If the value changes, the callback runs.

As we can see, this is much simpler than the old componentDidUpdate life cycle method.

Bonus: DOM refs

To access DOM elements, we need to use refs.

In a class component, we can create a ref and access it by writing:

We set the this.input in a callback that we pass into the ref prop of the input element.

Then we can call DOM methods on inputRef as we did in the onClick callback.

To do the same thing with function components, we use the useRef hook:

All we had to do is call the useRef hook to return a ref object.

Then we can call it in our onClick handler as we did in the button element.

The difference is that the DOM methods are under the current property instead of being at the top level.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

世界是平的

世界是平的

[美] 托马斯·弗里德曼 / 何帆、肖莹莹、郝正非 / 湖南科学技术出版社 / 2006-11 / 56.00元

当学者们讨论世界这20年发展的历史,并把目光聚集在2000年到2004年3月这一段时间时,他们将说些什么?9·11恐怖袭击还是伊拉克战争?或者,他们将讨论:科技的汇集与传播使得印度、中国和许多发展中国家成为世界商品和服务产品供给链上的一员,从而为世界大的发展中国家中的中产阶级带来了大量的财富,使这两个国家在全球化浪潮中占据更有利的位置?随着世界变得平坦,我们必须以更快的速度前进,才能在竞争中赢得胜......一起来看看 《世界是平的》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具