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

What's the difference between react hook and class?

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

Share

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

This article mainly introduces "what is the difference between react hook and class". In daily operation, I believe many people have doubts about the difference between react hook and class. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "what is the difference between react hook and class?" Next, please follow the editor to study!

Differences: 1, the writing of hooks is simpler than class; 2, the business code of hooks is more aggregated than class; 3, the logic reuse of class components usually uses render props and HOC, while react hooks provides custom hooks to reuse logic.

The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.

What are the differences between react hooks and class components? Let's compare react hooks and class components and talk about their differences.

Problems solved by react-hooks

A function component cannot have its own state (state). Before hooks, the function component was stateless, and the state of the parent component was obtained through props, but hooks provided useState to maintain the state within the function component.

The lifecycle of a component cannot be monitored in a function component. UseEffect aggregates multiple lifecycle functions.

The life cycle of class components is more complex (it varies greatly from version 15 to version 16).

Class component logic is difficult to HOC,render props.

The advantages of hooks over class (contrast) 1. The writing method is more concise.

Let's take the simplest counter as an example:

Class component

Class ExampleOfClass extends Component {constructor (props) {super (props) this.state = {count: 1}} handleClick = () = > {let {count} = this.state this.setState ({count: count+1})} render () {const {count} = this.state return (

You click {count}

Click)}}

Hooks

Function ExampleOfHooks () {const [count, setCount] = useState (0) const handleClick = () = > {setCount (count + 1)} return (

You click {count}

Click)}

You can see that the code using hooks is more concise and clear than the class component code.

2. Business codes are more aggregated.

When using class components, there is often a situation where a function occurs in two lifecycle functions, and sometimes you may forget to write separately. For example:

Let timer = nullcomponentDidMount () {timer = setInterval (() = > {/ /...}, 1000)} /... componentWillUnmount () {if (timer) clearInterval (timer)}

Because adding a timer and clearing a timer are in two different life cycle functions, there may be a lot of other business code in the middle, so you may forget to clear the timer. If you do not add a clear timer function when the component is unloaded, it may cause memory leaks, network requests and other problems.

But using hooks makes the code more centralized and easier for us to manage, and it's not easy to forget:

UseEffect (() = > {let timer = setInterval (() = > {/ /...}, 1000) return () = > {if (timer) clearInterval (timer)}}, [/ /...]) 3, logic reuse is convenient

Logical reuse of class components is usually done in two ways: render props and HOC. React hooks provides custom hooks to reuse logic.

The following example is to obtain the logical reuse of the position of the mouse on the page:

Reuse of class components in render props mode

Import React, {Component} from 'react'class MousePosition extends Component {constructor (props) {super (props) this.state = {x: 0, y: 0}} handleMouseMove = (e) = > {const {clientX, clientY} = e this.setState ({x: clientX, y: clientY})} componentDidMount () {document.addEventListener (' mousemove') This.handleMouseMove)} componentWillUnmount () {document.removeEventListener ('mousemove', this.handleMouseMove)} render () {const {children} = this.props const {x, y} = this.state return ({children ({x) Y})})} / / use class Index extends Component {constructor (props) {super (props)} render () {return ({({x, y})) = > {return (

X: {x}, y: {y}

)})}} export default Index

Custom hooks reuse

Import React, {useEffect, useState} from 'react'function usePosition () {const [x, setX] = useState (0) const [y, setY] = useState (0) const handleMouseMove = (e) = > {const {clientX, clientY} = e setX (clientX) setY (clientY)} useEffect (() = > {document.addEventListener (' mousemove', handleMouseMove) return () = > {document.removeEventListener ('mousemove', handleMouseMove)}}) return [{x Y}]} / / use function Index () {const [position] = usePosition () return

X: {position.x}, y: {position.y}

)} export default Index

It is obvious that using hooks is more convenient for logic reuse, and the logic is clearer when using it.

Some common API in hooks use 1, useState

Grammar

Const [value, setValue] = useState (0)

This syntax is the array structure of ES6. The first value of the array is the declared state, and the second value is the state change function.

Each frame has a separate state.

Personal understanding is that the independent state of each frame is realized by the method of closure.

Function Example () {const [val, setVal] = useState (0) const timeoutFn = () = > {setTimeout () = > {/ / the value obtained is the state in which the button was clicked, not the latest status console.log (val)}, 1000)} return (

{val}

SetVal (val+1)} > + alertNumber)}

When the status of the component or props is updated, the function component will be re-called for rendering, and each rendering will have its own independent props and state, which will not affect other renderings.

2 、 useEffect

Grammar

UseEffect (() = > {/ / handler function... Return () = > {/ / clean side effect}}, [/ / dep...])

UseEffect receives a callback function and a dependency, and executes the callback function only when the dependency changes. UseEffect is similar to the life cycle functions of class components didMount, didUpdate, and willUnmount.

Pay attention

UseEffect is asynchronous and executes only after component rendering is complete

The callback function of useEffect can only return a handler that clears side effects or does not return

If the dependency passed in by useEffect is an empty array, then the function inside useEffect will only be executed once

3 、 useMemo 、 useCallback

UseMemo and useCallback are mainly used to reduce the number of updates and optimize the performance of components.

UseMemo receives a callback function and a dependency, and the callback function is re-executed only when the dependency changes.

UseCallback receives a callback function and a dependency and returns the memorize version of the callback function, only when the dependency changes again will the new memorize version be renewed.

Grammar

Const memoDate = useMemo (() = > data, [/ / dep...]) const memoCb = useCallback (() = > {/ /...}, [/ / dep...])

When optimizing the performance of components, we usually use React.PureComponent,PureComponent to compare money in shouldUpdate for class components to determine whether they need to be updated; for functional components, we generally use React.memo. However, when using react hooks, because each render update is independent (a new state is generated), it will be re-rendered even if React.memo is used.

For example, in the following scenario, after changing the name value of the child component, the child component will also be re-rendered because the parent component will generate a new value each time the parent component is updated (the addAge function will change).

Function Parent () {const [name, setName] = useState ('cc') const [age, setAge] = useState (22) const addAge = () = > {setAge (age + 1)} return (

Parent component

SetName (e.target.value)} / >

Age: {age}

-

)} const Child = memo ((props) = > {const {addAge} = props console.log ('child component update') return

Sub-component

Click)})

Optimize with useCallback

Function Parent () {const [name, setName] = useState ('cc') const [age, setAge] = useState (22) const addAge = useCallback (() = > {setAge (age + 1)}, [age]) return (

Parent component

SetName (e.target.value)} / >

Age: {age}

-

)} const Child = memo ((props) = > {const {addAge} = props console.log ('child component update') return

Sub-component

Click)})

The memorize function is regenerated only when the dependency of useCallback changes. So when you change the state of name, addAge will not change.

4 、 useRef

UseRef is similar to react.createRef.

Const node = useRef (initRef)

UseRef returns a mutable ref object whose current property is initialized to the passed parameter (initRef)

Acting on DOM

Const node = useRef (null)

This allows you to access the DOM element through the node.current attribute.

It is important to note that the objects created by useRef remain the same throughout the life cycle of the component, that is, each time you re-render the function component, the returned ref object is the same (with React.createRef, the ref is recreated each time the component is re-rendered).

5 、 useReducer

UseReducer is similar to reducer in redux.

Grammar

Const [state, dispatch] = useReducer (reducer, initstate)

UseReducer passes in a calculation function and initializes state, similar to redux. We can access the status through the returned state, and we can modify the status through dispatch.

Const initstate = 0 function reducer (state, action) {switch (action.type) {case 'increment': return {number: state.number + 1}; case' decrement': return {number: state.number-1}; default: throw new Error ();} function Counter () {const [state, dispatch] = useReducer (reducer, initstate) Return (Count: {state.number} dispatch ({type: 'increment'})} > + dispatch ({type:' decrement'})} > -)} 6, useContext

Through useContext, we can get the context provided by the upper components more easily.

Parent component

Import React, {createContext, Children} from 'react'import Child from'. / child'export const MyContext = createContext () export default function Parent () {return (

Parent

)}

Sub-component

Import React, {useContext} from 'react'import {MyContext} from'. / parent'export default function Parent () {const data = useContext (MyContext) / / get the context console.log (data) return provided by the parent component (

Child

)}

Use steps

Parent component creates and exports context:export const MyContext = createContext ()

The parent component uses provider and value to provide values:

The child component imports the context:import {MyContext} from'. / parent' of the parent component

Get the value provided by the parent component: const data = useContext (MyContext)

In most cases, however, we do not recommend using context because it increases the coupling of components.

7 、 useLayoutEffect

UseEffect will not be executed until all rendering is complete; useLayoutEffect will be executed after the browser layout and before painting, and the plunger DOM; can use it to read the DOM layout and trigger re-rendering synchronously.

Export default function LayoutEffect () {const [color, setColor] = useState ('red') useLayoutEffect (() = > {alert (color) / / will block the rendering of DOM}); useEffect (() = > {alert (color) / / will not block}) return (color setColor (' red')} > red setColor ('yellow')} > yellow)}

In the above example, useLayoutEffect is executed before painting, and useEffect is executed after painting.

Hooks allows functional components to have an internal state and life cycle, use hooks to make the code more brief, custom hooks facilitates the reuse of logic, and gets rid of the this problem of class components; but there are some closure problems when using hooks, which need to be used carefully.

At this point, the study of "what is the difference between react hook and class" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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