Replacing React Lifecycle Methods with Hooks: A Comprehensive Guide

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

内容简介: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.


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

查看所有标签

猜你喜欢:

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

PHP+MySQL八大动态Web应用实战

PHP+MySQL八大动态Web应用实战

Jono Bacom / 吴连河、李剑 / 电子工业出版社 / 2008-6 / 68.00元

本书详细介绍了利用PHP+MySQL开发常见类型Web应用程序的完整设计和编码技术,并对整体设计与关键代码给予了细致、深入的剖析。其内容注重实践,提供了翔实完整的实战代码;思路独树一帜,突破过多描述语言细节的窠臼;行文风趣幽默,轻松调侃中将项目的完整设计过程分析得一清二楚。书中的示例项目完整而实用,读者甚至无需任何改动即可在实际中加以运用。. 本书适合对PHP/MySQL有初步了解但缺乏完整......一起来看看 《PHP+MySQL八大动态Web应用实战》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

html转js在线工具
html转js在线工具

html转js在线工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具