What are the differences between react hook and class?
Differences: 1. Hooks are written more concisely than classes; 2. The business code of hooks is more aggregated than classes; 3. Logic reuse of class components usually uses render props and HOC, while react hooks provide Use 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
Function components cannot have their own state. Before hooks, function components were stateless, and the state of the parent component was obtained through props, but hooks provide useState to maintain the internal state of the function component.
The life cycle of the component cannot be monitored in function components. useEffect aggregates multiple life cycle functions. The life cycle of
class components is more complicated (the changes are big from version 15 to version 16).
class component logic is difficult to reuse (HOC, render props).
The benefits of hooks compared to classes (comparison)
1. The writing method is more concise
We use the simplest counter For 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 ( <div> <p>you click { count }</p> <button onClick={this.handleClick}>点击</button> </div> ) } }
hooks
function ExampleOfHooks() { const [count, setCount] = useState(0) const handleClick = () => { setCount(count + 1) } return ( <div> <p>you click { count }</p> <button onClick={handleClick}>点击</button> </div> ) }
You can see that the code using hooks is compared with the class component code More concise and clear.
2. The business code is more aggregated
When using class components, it often happens that a function appears in two life cycle functions. Writing them separately may sometimes cause problems. forget. For example:
let timer = null componentDidMount() { timer = setInterval(() => { // ... }, 1000) } // ... componentWillUnmount() { if (timer) clearInterval(timer) }
Since adding a timer and clearing a timer are in two different life cycle functions, there may be a lot of other business code in between, so you may forget to clear the timer if the component is uninstalled. Failure to add a clear timer function may cause problems such as memory leaks and constant network requests.
But using hooks can make the code more centralized, convenient for us to manage, and not easy to forget:
useEffect(() => { let timer = setInterval(() => { // ... }, 1000) return () => { if (timer) clearInterval(timer) } }, [//...])
3. Convenient logic reuse
Logic reuse of class components usually uses render props and HOC. React hooks provides custom hooks to reuse logic.
The following takes the logic reuse of obtaining the mouse position on the page as an example:
Class component render props method reuse
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( <div> { children({x, y}) } </div> ) } } // 使用 class Index extends Component { constructor(props) { super(props) } render() { return ( <MousePosition> { ({x, y}) => { return ( <div> <p>x:{x}, y: {y}</p> </div> ) } } </MousePosition> ) } } export default Index
Custom hooks method 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} ] } // 使用 function Index() { const [position] = usePosition() return( <div> <p>x:{position.x},y:{position.y}</p> </div> ) } export default Index
It can be clearly seen that using hooks is more convenient for logic reuse, and the logic is clearer when used.
Some common API uses of hooks
1, useState
Syntax
const [value, setValue] = useState(0)
This syntax is the ES6 array structure. The first value of the array is the declared state, and the second value is the state change function.
Each frame has an independent state
My personal understanding is that the independent state of each frame is achieved using the closure method.
function Example() { const [val, setVal] = useState(0) const timeoutFn = () => { setTimeout(() => { // 取得的值是点击按钮的状态,不是最新的状态 console.log(val) }, 1000) } return ( <> <p>{val}</p> <button onClick={()=>setVal(val+1)}>+</button> <button onClick={timeoutFn}>alertNumber</button> </> ) }
When the component's status or props are updated, the function component will be re-invoked for rendering, and each rendering is independent and has its own independent props and state, and will not affect other renderings.
2. useEffect
Syntax
useEffect(() => { //handler function... return () => { // clean side effect } }, [//dep...])
useEffect receives a callback function and dependencies when the dependencies change Only then will the callback function inside be executed. useEffect is similar to the life cycle functions of class components didMount, didUpdate, and willUnmount.
Note
useEffect is asynchronous and will not be executed until the component is rendered
The callback function of useEffect can only return a processing function that clears side effects or does not return
If the dependency passed in by useEffect is an empty array, the function inside useEffect will only be executed once
3. useMemo, useCallback
useMemo and useCallback are mainly used to reduce the number of component updates and optimize component performance.
useMemo receives a callback function and dependencies, and the callback function will be re-executed only when the dependencies change.
useCallback receives a callback function and dependencies, and returns the memorized version of the callback function. The memorized version will only be re-memorized when the dependencies change.
Syntax
const memoDate = useMemo(() => data, [//dep...]) const memoCb = useCallback(() => {//...}, [//dep...])
When optimizing component performance, we generally use React.PureComponent for class components. PureComponent will perform a comparison on shouldUpdate. Determine whether updates are needed; for function components we generally use React.memo. But when using react hooks, since each rendering update is independent (new state is generated), even if React.memo is used, it will still be re-rendered.
比如下面这种场景,改变子组件的name值后由于父组件更新后每次都会生成新值(addAge函数会改变),所以子组件也会重新渲染。
function Parent() { const [name, setName] = useState('cc') const [age, setAge] = useState(22) const addAge = () => { setAge(age + 1) } return ( <> <p>父组件</p> <input value={name} onChange={(e) => setName(e.target.value)} /> <p>age: {age}</p> <p>-------------------------</p> <Child addAge={addAge} /> </> ) } const Child = memo((props) => { const { addAge } = props console.log('child component update') return ( <> <p>子组件</p> <button onClick={addAge}>click</button> </> ) })
使用useCallback优化
function Parent() { const [name, setName] = useState('cc') const [age, setAge] = useState(22) const addAge = useCallback(() => { setAge(age + 1) }, [age]) return ( <> <p>父组件</p> <input value={name} onChange={(e) => setName(e.target.value)} /> <p>age: {age}</p> <p>-------------------------</p> <Child addAge={addAge} /> </> ) } const Child = memo((props) => { const { addAge } = props console.log('child component update') return ( <> <p>子组件</p> <button onClick={addAge}>click</button> </> ) })
只有useCallback的依赖性发生变化时,才会重新生成memorize函数。所以当改变name的状态是addAge不会变化。
4、useRef
useRef类似于react.createRef。
const node = useRef(initRef)
useRef 返回一个可变的 ref 对象,其 current 属性被初始化为传入的参数(initRef)
作用在DOM上
const node = useRef(null) <input ref={node} />
这样可以通过node.current属性访问到该DOM元素。
需要注意的是useRef创建的对象在组件的整个生命周期内保持不变,也就是说每次重新渲染函数组件时,返回的ref 对象都是同一个(使用 React.createRef ,每次重新渲染组件都会重新创建 ref)。
5、useReducer
useReducer类似于redux中的reducer。
语法
const [state, dispatch] = useReducer(reducer, initstate)
useReducer传入一个计算函数和初始化state,类似于redux。通过返回的state我们可以访问状态,通过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} <button onClick={() => dispatch({type: 'increment'})}>+</button> <button onClick={() => dispatch({type: 'decrement'})}>-</button> </> ) }
6、useContext
通过useContext我们可以更加方便的获取上层组件提供的context。
父组件
import React, { createContext, Children } from 'react' import Child from './child' export const MyContext = createContext() export default function Parent() { return ( <div> <p>Parent</p> <MyContext.Provider value={{name: 'cc', age: 21}}> <Child /> </MyContext.Provider> </div> ) }
子组件
import React, { useContext } from 'react' import { MyContext } from './parent' export default function Parent() { const data = useContext(MyContext) // 获取父组件提供的context console.log(data) return ( <div> <p>Child</p> </div> ) }
使用步骤
- 父组件创建并导出
context:export const MyContext = createContext()
- 父组件使用
provider
和value
提供值:<MyContext.provide value={{name: 'cc', age: 22}} />
- 子组件导入父组件的
context:import { MyContext } from './parent'
- 获取父组件提供的值:
const data = useContext(MyContext)
不过在多数情况下我们都不建议使用context
,因为会增加组件的耦合性。
7、useLayoutEffect
useEffect 在全部渲染完毕后才会执行;useLayoutEffect 会在 浏览器 layout之后,painting之前执行,并且会柱塞DOM;可以使用它来读取 DOM 布局并同步触发重渲染。
export default function LayoutEffect() { const [color, setColor] = useState('red') useLayoutEffect(() => { alert(color) // 会阻塞DOM的渲染 }); useEffect(() => { alert(color) // 不会阻塞 }) return ( <> <div id="myDiv" style={{ background: color }}>颜色</div> <button onClick={() => setColor('red')}>红</button> <button onClick={() => setColor('yellow')}>黄</button> </> ) }
上面的例子中useLayoutEffect会在painting之前执行,useEffect在painting之后执行。
hooks让函数组件拥有了内部状态、生命周期,使用hooks让代码更加的简介,自定义hooks方便了对逻辑的复用,并且摆脱了class组件的this问题;但是在使用hooks时会产生一些闭包问题,需要仔细使用。
【相关推荐:Redis视频教程】
The above is the detailed content of What are the differences between react hook and class?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Concepts and instances of classes and methods Class (Class): used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes. Method: Function defined in the class. Class construction method __init__(): The class has a special method (construction method) named init(), which is automatically called when the class is instantiated. Instance variables: In the declaration of a class, attributes are represented by variables. Such variables are called instance variables. An instance variable is a variable modified with self. Instantiation: Create an instance of a class, a specific object of the class. Inheritance: that is, a derived class (derivedclass) inherits the base class (baseclass)

Class is a keyword in Python, used to define a class. The method of defining a class: add a space after class and then add the class name; class name rules: capitalize the first letter. If there are multiple words, use camel case naming, such as [class Dog()].

jQuery is a classic JavaScript library that is widely used in web development. It simplifies operations such as handling events, manipulating DOM elements, and performing animations on web pages. When using jQuery, you often encounter situations where you need to replace the class name of an element. This article will introduce some practical methods and specific code examples. 1. Use the removeClass() and addClass() methods jQuery provides the removeClass() method for deletion

When writing PHP code, using classes is a very common practice. By using classes, we can encapsulate related functions and data in a single unit, making the code clearer, easier to read, and easier to maintain. This article will introduce the usage of PHPClass in detail and provide specific code examples to help readers better understand how to apply classes to optimize code in actual projects. 1. Create and use classes In PHP, you can use the keyword class to define a class and define properties and methods in the class.

Vue error: Unable to use v-bind to bind class and style correctly, how to solve it? In Vue development, we often use the v-bind instruction to dynamically bind class and style, but sometimes we may encounter some problems, such as being unable to correctly use v-bind to bind class and style. In this article, I will explain the cause of this problem and provide you with a solution. First, let’s understand the v-bind directive. v-bind is used to bind V

Background Recently, key business codes have been encrypted for the company framework to prevent the engineering code from being easily restored through decompilation tools such as jd-gui. The configuration and use of the related obfuscation scheme are relatively complex and there are many problems for the springboot project, so the class files are encrypted and then passed The custom classloder is decrypted and loaded. This solution is not absolutely safe. It only increases the difficulty of decompilation. It prevents gentlemen but not villains. The overall encryption protection flow chart is shown in the figure below. Maven plug-in encryption uses custom maven plug-in to compile. The class file specified is encrypted, and the encrypted class file is copied to the specified path. Here, it is saved to resource/corecla.

How jquery determines whether an element has a class: 1. Determine whether an element has a certain class through the "hasClass('classname')" method; 2. Determine whether an element has a certain class through the "is('.classname')" method.
![How to solve the '[Vue warn]: v-bind:class/ :class' error](https://img.php.cn/upload/article/000/465/014/169300902772563.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
How to solve the "[Vuewarn]:v-bind:class/:class" error During the development process of using Vue, we often encounter some error prompts. One of the common errors is "[Vuewarn]:v-bind:class" /:class" error. This error message usually appears when we use v-bind:class or :class attribute, indicating that Vue cannot correctly parse the class value we set. Then, if
