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.


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

查看所有标签

猜你喜欢:

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

PERL學習手札.

PERL學習手札.

簡信昌 / 上奇科技 / 20040816 / NT$ 390

1. 關於Perl 當你翻開這本書的時候,你也就進入了一個奇幻的世界。Perl確實是一種非常吸引人的程式語言,而之所以這麼引人入勝的原因不單單在於他的功能,也在於他寫作的方式,或說成為一種程式寫作的藝術。即使你只是每天埋首於程式寫作的程式設計師,也不再讓生活過份單調,至少你可以嘗試在程式碼中多一些變化。而且許多Perl的程式設計師已經這麼作了,這也是Perl的理念-「There is mor......一起来看看 《PERL學習手札.》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

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

在线图片转Base64编码工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器