Replacing React Lifecycle Methods with Hooks: A Comprehensive Guide

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

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


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

查看所有标签

猜你喜欢:

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

安全测试指南(第4版)

安全测试指南(第4版)

OWASP基金会 / 电子工业出版社 / 2016-7-1 / CNY 89.00

软件安全问题也许是这个时代面临的*为重要的技术挑战。Web应用程序让业务、社交等网络活动飞速发展,这同时也加剧了它们对软件安全的要求。我们急需建立一个强大的方法来编写和保护我们的互联网、Web应用程序和数据,并基于工程和科学的原则,用一致的、可重复的和定义的方法来测试软件安全问题。本书正是实现这个目标的重要一步,作为一本安全测试指南,详细讲解了Web应用测试的“4W1H”,即“什么是测试”、“为什......一起来看看 《安全测试指南(第4版)》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

MD5 加密
MD5 加密

MD5 加密工具