Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to transfer React from Class to Hooks

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "how to change React from Class to Hooks". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn "how to transfer React from Class to Hooks".

Why Hooks?

One of the big highlights of Hooks is the reuse of business logic. This is particularly evident in hooks. For example, in the usual class, if you want to listen for window size changes, you have to add listening events in the component after loading, but if this listening window size feature is needed in another place, this logic code cannot be reused and can only be rewritten in that component. But in hooks, we can encapsulate this part of the listening logic code in the way of hooks, which can be logically reused.

For Class

When using Class as the carrier of React:

Components do not inherit from each other, do not take advantage of the inherited feature of class UI is state-driven, and all methods are called internally or automatically as lifecycle methods. There are no features that can be called by instance methods of the class

For Function

A core of React is to implement a binding from State data to the View attempt level. Using functions is actually a better way to solve a mapping problem from State to View. However, there are two problems when using a function as the carrier of React, the preservation of the state in the function and the method of life cycle.

How does Hooks solve the above two problems: binding an external data to the execution of the function. When the data changes, the function can be automatically re-executed. In this way, any external data that affects the presentation of UI can be bound to the functional components of React through this mechanism.

Hooks hook understanding: hook a target result to a data source or event source that may change, then when the hooked data or event changes, the code that produces the target result will be re-executed to produce the updated result

Illustration: an Execution, such as the function component itself, can be bound to (hooked to) the traditional State, or URL, or even the size of the window. In this way, when the size of State, URL, and window changes, a function will be re-executed to produce the updated result.

Class & Hooks comparison

A functional component is more appropriate to express the execution of a React component than a Class component, because it is more consistent with a logical relationship such as State = > View. However, due to the lack of state, life cycle and other mechanisms, its function has been limited. Hooks solves the limited problems such as the state life cycle of function components as React carriers, and gives full play to its functions.

The hooked object in Hooks can be a separate data source or the result of another Hook execution, which brings the greatest benefit of Hooks: logic reuse.

Simplifies logic reuse

Class mode: using the design pattern of high-level components for logical reuse. For example, to reuse the function of a window resize, we need to define an outer component without UI, write the logical definition of the relevant resize, and then pass the data results to the subcomponents in the form of attributes. For a component to reuse this logic, it must be wrapped in the outer layer of the component and returned. For the whole, * * in order to pass an external state, we have to define an outer component without UI, which is just to encapsulate a piece of reusable logic. * * frequently used, each high-level component will have an extra layer of nodes, which will bring a great burden to debugging.

/ / higher-level components implement resize method reuse / / 1. Declaration of high-level components const withWindowSize = Component = > {/ / generate a high-level component WrappedComponent, which contains only logic class WrappedComponent extends React.PureComponent {constructor (props) {super (props); this.state = {size: this.getSize ()};} componentDidMount () {window.addEventListener ("resize", this.handleResize) } componentWillUnmount () {window.removeEventListener ("resize", this.handleResize);} getSize () {return window.innerWidth > 1000? "large": "small";} handleResize = () = > {const currentSize = this.getSize (); this.setState ({size: this.getSize ()});} render () {/ / pass the window size to the real business logic component return;}} return WrappedComponent;} / / 2. Component MyComponent uses the resize function class MyComponent extends React.Component {render () {const {size} = this.props; if (size = "small") return in high-level components; else return;}} / / uses withWindowSize to generate high-level components that generate size attributes and pass them to the real business component export default withWindowSize (MyComponent)

Hooks mode: if you implement resize, the window size is just an external data state. We use hooks to encapsulate it, but turn it into a data source that can be bound, and when the window size changes, this component will re-render the code more concise and intuitive, and will not generate additional component nodes.

/ / use the hooks method in Hooks for resize logical reuse / / define the hookconst getSize of useWindowSize = () = > {return window.innerWidth > 1000? "large": "small";} const useWindowSize = () = > {const [size, setSize] = useState (getSize ()); useEffect () = > {const handler = () = > {setSize (getSize ())}; window.addEventListener ('resize', handler); return () = > {window.removeEventListener (' resize', handler);};}, []); return size;} / / use this hookconst Demo = () = > {const size = useWindowSize (); if (size = "small") return in the function component; else return;}

Help to focus on separation

Hooks can aggregate code for the same business logic as much as possible. In Class components, the same business logic code has to be scattered in different lifecycle methods of class components.

Illustration: on the left is the Class component, and on the right is the function component with Hooks. Blue and yellow represent different business functions

How does Hooks save component state and usage lifecycle?

React provides a total of 10 Hooks,useState, useEffect, useCallback, useMemo, useRef, useContext, etc.

1. UseState: let the function have the ability to maintain the state

One of the principles we should follow is that state should never save values that can be calculated, such as:

The value passed from props. Sometimes the values passed by props cannot be used directly, but are calculated and then displayed on UI, such as sorting. So what we need to do is reorder every time we use it, or make use of some cache mechanism, instead of putting the results directly into the state.

The value read from URL. For example, sometimes you need to read the parameter in URL as part of the component state. Then we can read it from URL every time we need it, instead of reading it out and putting it directly into state.

The value read from cookie, localStorage. Generally speaking, it is also to read it directly every time you want to use it, rather than reading it and putting it into state.

2. UseEffect: side effects of execution

A side effect is a piece of code that has nothing to do with the result of the current execution. For example, to modify a variable outside the function, make a request. Form: useEffect (callback, dependencies). It covers three lifecycle methods: componentDidMount, componentDidUpdate and componentWillUnmount. In short, useEffect determines dependencies and executes each time the component render finishes.

Points you should pay attention to when using useEffect:

If there are no dependencies, it will be re-executed after each render

UseEffect (() = > {console.log ('re-render') / / execute after each render is completed})

An empty array, as a dependency, is triggered only when it is first executed, and the corresponding Class component is componentDidMount

UseEffect (() = > {console.log ('did mount') / / equivalent to componentDidMount}, [])

You can return a function to do some cleaning when the component is destroyed

Const [size,setResize] = useState ({}) useEffect (() = > {const handler = () = > {setResize ()} window.addEventListener ('resize',handler) return () = > {window.removeEventListener (' resize',handler)}}, []) these are all the contents of the article "how to transfer React from Class to Hooks". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report