search
HomeWeb Front-endJS TutorialWhat is a hook? Let's talk about two commonly used Hooks in React

This article will take you through hooks, talk about why it is recommended to use hooks for development, and introduce the two most commonly used Hooks in React. I hope it will be helpful to everyone!

What is a hook? Let's talk about two commonly used Hooks in React

Let me first introduce what a hook is

Hook is a new feature of React 16.8. It is specially used in functional components. It can replace react in class components. Other features are commonly used in actual work. [Related recommendations: Redis Video Tutorial]

Hooks are specially used to develop functional components and can be used to replace class components. Some life cycles to avoid confusion caused by a large number of this, so hooks facilitate development and make it easier for developers to understand the code

The above is a personal summary. For more reasons, please refer to the react official website:

https://react.docschina.org/docs/hooks-intro.html#motivation

useState

In code:

React. useState(0) is equivalent to this.state in the class component. Adding an attribute value

variable is equivalent to this.state in the class component. The value of variable

setVariable can be used to modify the variable The value can be equivalent to this.setState in the class component

import React,(useState) from 'react'
export default function useState_Demo() {
    const [variable, setVariable] = useState(0);//通过解构赋值,我们拿到的variable、setVariable
    function changeVariable(){
        setVariable((variable) => variable +1) //setVariable的回调中传进来的参数是variable
    }
    render (
        <div> 
            <button onclick = {change}>点我会使variable+1</button>
        </div>
    )
}

useEffect

In the code:

As can be seen from the following code, useEffect is used instead of in the class component The use of componentDidMoun, componentDidUpdate, and componentWillUnmount

import React,(useState, useEffect) from &#39;react&#39;
export default function useState_Demo() {
   const [variable, setVariable] = useState(0);//通过解构赋值,我们拿到的variable、setVariable
    
    useEffect(() => {
        //这个return是在该组件监测的数据变化时或者被卸载时调用的,被卸载时调用可以相当于componentWillUnmount钩子 
        return () => {
            console.log(&#39;该组件被卸载了&#39;)
        }
    }, [variable])//第二个参数传了[variable],表示检测variable的更新变化,一旦variable变化就会再次执行useEffect的回调
                  //第二个参数传了[],表示谁都不检测只执行一次useEffect的回调,相当于componentDidMount钩子
                  //第二个参数不传参,只要该组件有state变化就会执行useEffect的回调,相当于componentDidUpdate钩子
    function changeVariable(){
        setVariable((variable) => variable +1) //setVariable的回调中传进来的参数是variable
    }
    render (
        <div> 
            <button onclick = {change}>点我会使variable+1</button>
        </div>
    )
}

What you need to pay attention to when using hooks

1. Only use Hooks in the outermost layer of component functions, and do not call them in loops, conditions or nested functions. Hook

import React,(useEffect) from &#39;react&#39;
export default function useState_Demo() {
   //这里才是正确的
   useEffect(() => {})
    
   //错误1,使用了条件判断
   if(true) {
        useEffect(() => {})
   }
   //错误2,使用了循环
   while(true) {
        useEffect(() => {})
   }
  //错误3,使用了嵌套
  useEffect(() => {
      useEffect(() => {})
  })
}

2. Hook

import React,(useState, useEffect) from &#39;react&#39;
//错误1,在组件函数外使用了useState
const [variable, setVariable] = useState(0);
//错误2,在组件函数外使用了useEffect
useEffect(() => {})
export default function useState_Demo() {
   //在组件函数里使用才是正确的
   const [variable, setVariable] = useState(0);
}

3 cannot be used outside the function of the component. In order to avoid the above errors, you can install eslint-plugin-react-hooks ESLint plug-in to check code errors

Custom hook

Hook is a function. Custom hook is to facilitate sharing logic between components. In fact, it is to reuse functions. Encapsulation, the custom hook also calls the hook that comes with react. The name should start with use

//自定义hook
function useHook(initState) {
  const [variable, setVariable] = useState(initState)
  return variable;
}
//使用自定义hook
export default function useState_Demo() {
    const variableState = useHook(0)
}

You may be wondering, will the same Hook be used in multiple components to share state?

The answer is: no. Because each call to the hook that comes with react is independent and does not affect each other, so the custom hook is independent and does not affect each other when called multiple times.

For more programming-related knowledge, please visit: Introduction to programming! !

The above is the detailed content of What is a hook? Let's talk about two commonly used Hooks in React. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
react中canvas的用法是什么react中canvas的用法是什么Apr 27, 2022 pm 03:12 PM

在react中,canvas用于绘制各种图表、动画等;可以利用“react-konva”插件使用canvas,该插件是一个canvas第三方库,用于使用React操作canvas绘制复杂的画布图形,并提供了元素的事件机制和拖放操作的支持。

react中antd和dva是什么意思react中antd和dva是什么意思Apr 21, 2022 pm 03:25 PM

在react中,antd是基于Ant Design的React UI组件库,主要用于研发企业级中后台产品;dva是一个基于redux和“redux-saga”的数据流方案,内置了“react-router”和fetch,可理解为应用框架。

React是双向数据流吗React是双向数据流吗Apr 21, 2022 am 11:18 AM

React不是双向数据流,而是单向数据流。单向数据流是指数据在某个节点被改动后,只会影响一个方向上的其他节点;React中的表现就是数据主要通过props从父节点传递到子节点,若父级的某个props改变了,React会重渲染所有子节点。

react中为什么使用nodereact中为什么使用nodeApr 21, 2022 am 10:34 AM

因为在react中需要利用到webpack,而webpack依赖nodejs;webpack是一个模块打包机,在执行打包压缩的时候是依赖nodejs的,没有nodejs就不能使用webpack,所以react需要使用nodejs。

react中forceupdate的用法是什么react中forceupdate的用法是什么Apr 19, 2022 pm 12:03 PM

在react中,forceupdate()用于强制使组件跳过shouldComponentUpdate(),直接调用render(),可以触发组件的正常生命周期方法,语法为“component.forceUpdate(callback)”。

react是组件化开发吗react是组件化开发吗Apr 22, 2022 am 10:44 AM

react是组件化开发;组件化是React的核心思想,可以开发出一个个独立可复用的小组件来构造应用,任何的应用都会被抽象成一颗组件树,组件化开发也就是将一个页面拆分成一个个小的功能模块,每个功能完成自己这部分独立功能。

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

react和reactdom有什么区别react和reactdom有什么区别Apr 27, 2022 am 10:26 AM

react和reactdom的区别是:ReactDom只做和浏览器或DOM相关的操作,例如“ReactDOM.findDOMNode()”操作;而react负责除浏览器和DOM以外的相关操作,ReactDom是React的一部分。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software