首页 > 其他分享 >How Do React Hooks Actually Work?

How Do React Hooks Actually Work?

时间:2025-01-04 15:24:34浏览次数:6  
标签:Do counterValue const Hooks Work state useState hooks newValue

React hooks allow us to use React features without writing a class

  • state (useState, useReducer)
  • component lifecycle (useEffect)
  • much more(useRef, useContext, etc.)

Questions surrounding React Hooks

  • Why can't we call hooks inside loops or conditions?
  • Why isn't there a hook for this?
  • Why isn't there a hook for that?

Why can't we call hooks inside Loops Or Conditions?

Why do hooks reply on call order?

1. Hooks are all about Arrays

Example for hook

  • eg01
const ReactX = (() => {
    const useState = (initialValue) => {

        let state = initialValue;

        const setterFunction = (newValue) => {
            console.log('newValue: ', newValue)
            state = newValue;
        }
        return [
            state,
            setterFunction
        ]
    }
    return {
        useState,
    };
})();

const { useState } = ReactX;

const Component = () => {
    const [counterValue, setCounterValue] = useState(1);
    console.log(counterValue);
    if (counterValue !== 2) {
        setCounterValue(2);
    }
}

Component(); // 1
Component(); // 1

  • eg02
const ReactX = (() => {
    let state;
    const useState = (initialValue) => {
        if (state === undefined) {
            state = initialValue;
        }
        const setterFunction = (newValue) => {
            state = newValue;
        }
        return [
            state,
            setterFunction
        ]
    }
    return {
        useState,
    };
})();

const { useState } = ReactX;

const Component = () => {
    const [counterValue, setCounterValue] = useState(1);
    console.log(counterValue);
    if (counterValue !== 2) {
        setCounterValue(2);
    }
}

Component(); // 1
Component(); // 2
  • eg03
const ReactX = (() => {
  let state = [];
  let index = 0;
    const useState = (initialValue) => {
      const localIndex = index;
      index++;
      
        if(state[localIndex] === undefined) {
          state[localIndex] = initialValue;
        }
        const setterFunction = (newValue) => {
            console.log('newValue: ', newValue)
            state[localIndex] = newValue;
        }
        return [
            state[localIndex],
            setterFunction
        ]
    }
    const resetIndex = () => {
      index = 0;
    }
    return {
        useState,
        resetIndex,
    };
})();

const { useState, resetIndex } = ReactX;

const Component = () => {
    const [counterValue, setCounterValue] = useState(1);
    console.log(counterValue);
    if (counterValue !== 2) {
        setCounterValue(2);
    }
}

Component(); // 1
resetIndex();
Component(); // 2

So why can't we call hoos inside loops or conditions?
the state is just an array and useState access this array using indexes
if we called useState inside loops or conditions, those indexes may be different on every render
and this would cause each of the hooks to use the wrong state, which would result into application-breaking bugs.

  • eg03
const ReactX = (() => {
  let hooks = [];
  let index = 0;
    const useState = (initialValue) => {
      const localIndex = index;
      index++;
        if(hooks[localIndex] === undefined) {
          hooks[localIndex] = initialValue;
        }
        const setterFunction = (newValue) => {
            console.log('newValue: ', newValue)
            hooks[localIndex] = newValue;
        }
        return [
            hooks[localIndex],
            setterFunction
        ]
    }
    
    const useEffect = (callback, dependencyArray) => {
      let hasChanged = true;
      
      const oldDependencies = hooks[index];
      
      if(oldDependencies) {
        hasChanged = false
        dependencyArray.forEach((dependency, index) => {
           const oldDependency = oldDependencies[index];
          const areTheSame = Object.is(dependency, oldDependency);
          if(!areTheSame) {
            hasChange = true;
          }
        })
      }
      
      if(hasChanged) {
        callback();
      }
      hooks[index] = dependencyArray;
      index++;
    }
    const resetIndex = () => {
      index = 0;
    }
    return {
        useState,
        useEffect,
        resetIndex,
    };
  
  
  
})();

const { useState, useEffect, resetIndex }= ReactX;

const Component = () => {
    const [counterValue, setCounterValue] = useState(1);
    const [name, setName] = useState("Thomas");
  
    console.log(counterValue);
    console.log(name)
    
    useEffect(() => {
      console.log('useEffect for name')
    }, [name])
    
    if (counterValue !== 2) {
        setCounterValue(2);
    }
  
    if(name !== "Jack" && counterValue === 2) {
      setName("Jack")
    }
}

Component();
resetIndex();
Component(); 

// ============ ouput ============
1
'Thomas'
'useEffect for name'
'newValue: ' 2
2
'Thomas'
'newValue: ' 'Jack'

2 Rules
  1. Composition = hooks don't conflit with each other.
  2. Debugging = bugs should be easy to find

How can useState() be part of rendering ?

  • rendering is handled by React DOM but we aren't import useState() from React DOM
  • when useState() get called, the call gets forwarded to dispatcher

标签:Do,counterValue,const,Hooks,Work,state,useState,hooks,newValue
From: https://www.cnblogs.com/openmind-ink/p/18651918

相关文章

  • 使用Docker部署简单实用的 IP查询工具箱 【复制成功,复制和转载请标注本文地址】
    通过这个工具,可以查看需要查询的公网IP地址、连通性、检查WebRTC连接、检查DNS、网速测试、MTR测试等。假如你不想部署到本地,也可以直接体验官方网址:https://ipcheck.ing下面就开始部署:只需要一行命令就可以一键安装到docker,端口自行修改。部署起来非常的简单,使用SSH终端......
  • ubuntu 使用samba与windows共享文件[注意权限配置]
    在Ubuntu上使用Samba服务与Windows系统共享文件,需要正确配置Samba服务以及相应的权限。以下是详细的步骤:安装Samba首先,确保你的Ubuntu系统上安装了Samba服务。sudoaptupdatesudoaptinstallsamba配置Samba安装完成后,需要配置Samba共享。编辑Samba的配置文件。su......
  • macOS、Windows 安装Postman免登录版
    Postman作为一款流行的API调试工具,一直深受开发者喜爱。然而,最近Postman的更新却让许多用户感到不满。新版本不仅阉割了导入本地备份数据包的功能,还无法新建collection,只有历史记录列表了,这使得许多用户无法正常使用Postman。如果你也对Postman的新版本感到失望,那么不妨......
  • How Does React actually work ?
    ThebasicconceptsofReactreconciliationvirtualDOMrenderingdiffingalgorithmpre-knowledgeunderstandthedifferencebetweenReactcomponents,elementsandcomponentWhatisaReactcomponent?Reactcomponent=classorafunctionthatoutpu......
  • window 禁止自动更新,无副作用
    方式1手动:1.运行(win+r),输入regedit。2.打开计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings。3.新建DWORD(32位)值(D),重命名FlightSettingsMaxPauseDays。4.双击,修改基数为十进制,修改数值数据是“暂停更新的天数”。方式2自动:运行(win+r),输入......
  • dsparse.dll未被指定在Windows运行,代码0xc0000020或0xc000012f解决办法
    在大部分情况下出现我们运行或安装软件,游戏出现提示丢失某些DLL文件或OCX文件的原因可能是原始安装包文件不完整造成,原因可能是某些系统防护软件将重要的DLL文件识别为可疑,阻止并放入了隔离单里,还有一些常见的DLL文件缺少是因为系统没有安装齐全的微软运行库,还有部分情况是因......
  • dsprop.dll未被指定在Windows运行,代码0xc0000020或0xc000012f解决办法
    在大部分情况下出现我们运行或安装软件,游戏出现提示丢失某些DLL文件或OCX文件的原因可能是原始安装包文件不完整造成,原因可能是某些系统防护软件将重要的DLL文件识别为可疑,阻止并放入了隔离单里,还有一些常见的DLL文件缺少是因为系统没有安装齐全的微软运行库,还有部分情况是因......
  • dsreg.dll未被指定在Windows运行,代码0xc0000020或0xc000012f解决办法
    在大部分情况下出现我们运行或安装软件,游戏出现提示丢失某些DLL文件或OCX文件的原因可能是原始安装包文件不完整造成,原因可能是某些系统防护软件将重要的DLL文件识别为可疑,阻止并放入了隔离单里,还有一些常见的DLL文件缺少是因为系统没有安装齐全的微软运行库,还有部分情况是因......
  • 应用Docker快速实现 JMeter + InfluxDB + Grafana 监控方案
            Docker是一个基于 Go语言 并遵从Apache2.0协议开源的应用容器引擎,其能够让开发人员打包他们的开发的应用以及依赖包到一个轻量级、可移植的容器中,然后再发布到测试和线上环境,当然也可以实现虚拟化。容器是完全使用沙箱机制,可应用于自动化测试、持续集成......
  • Docker实战
    Docker介绍什么是Docker?说实话关于Docker是什么并不太好说,下面我通过四点向你说明Docker到底是个什么东西。Docker是世界领先的软件容器平台,基于Go语言进行开发实现。Docker能够自动执行重复性任务,例如搭建和配置开发环境,从而解放开发人员。用户可以方便地创建和......