搜索
首页web前端js教程React 中的 useEffect 实际上是一个 Effect 吗?

反应:我选择你

我开始了我自己的 React JS 之旅,作为我的入门 Pokemon 来探索 Javascript 框架世界。乍一看,我爱上了它,因为它减少了大量命令式 DOM 操作代码。我真的很喜欢框架根据状态自动操作 DOM 的想法。

Is useEffect in React is actually an Effect?

一开始,我没有考虑 React 的大小和它消耗的内存,这可以在重量上击败 Snorlax
学习 React 后,我​​接触到了很多框架,比如 Vue、Angular、Svelte。当我终于接触到 SolidJS 时,我的眼睛睁开了

Is useEffect in React is actually an Effect?

我开始关注 SolidJS 的作者 Ryan Carniato 的直播和文章。他完全改变了我看待框架的方式。我开始了解 Javascript 框架的反应系统。当我回头看到 My Starter Pokemon React 及其反应性和渲染系统时,我无法控制自己的笑

Is useEffect in React is actually an Effect?

好像我从一开始就被愚弄了。为什么每当状态发生变化时都需要重新运行一切?如果是这样那么为什么我们真的需要一个名为 useEffect 的钩子来充当副作用。

现在进入文章标题

我将这篇文章命名为 React 中的 useEffect 实际上是一个 Effect 吗?就像Vegapunk 睁开了人们关于政府的眼睛(抱歉剧透了 OP 粉丝) 一样,让你对 React 睁开眼睛。对此有很多值得批评的想法。所以今天是使用Effect的日子,他隐藏了自己的真名,撒谎最多。

如果你是初学者或者你问一些 React 初学者,他们会对 useEffect 的解释为

只要依赖数组中的值发生变化就会重新运行的函数。

如果你是那个人,你真的很幸运知道你被教导是错误的真相。每当发生变化时,React 就会重新运行,所以不需要重新运行函数,因为不需要它。下面我就来解释一下真相

效果的真正含义是什么?

让我解释一下效果的真正含义。在Reactivity系统中,Effect实际上被称为Side Effect。让我们从一个例子开始

const name = "John Doe"
createEffect(()=>{
    console.log("New name", name)
},[name])

此处 createEffect 函数接受一个函数,只要第二个参数中的 Array 中的值发生变化,该函数就会重新运行。 createEffect 中的函数是名称的副作用,换句话说,该函数取决于状态名称。每当名称的值更改时,副作用就会重新运行。这就是副作用真正的含义。

React 实际上做了什么?

让我用 React 编写相同的代码

const [name, setName] = useState("John Doe")
useEffect(()=>{
    console.log("New name", name)
},[name])
setName("Jane Doe")

每当调用 setName 时,useEffect 都会重新运行。我完全明白了。让我通过简单地删除 useEffect 来给出等效代码。它也有效,因为 React 的 useState 不会创建任何反应状态

const [name, setName] = useState("John Doe")
console.log("New name", name)
setName("Jane Doe")

TADA! 它在 React 中工作得很好,因为每当 useState 的状态时它都会重新运行
变化。我再举一个例子来解释一下useEffect。

const [name, setName] = useState("John Doe")
const [age, setAge] = useState(18)
console.log("New name", name)
setAge(21)

现在每当年龄改变时,console.log("New name", name)也会被执行,这不是我们想要的。所以我们用 useEffect 包装它。

const [name, setName] = useState("John Doe")
const [age, setAge] = useState(18)
useEffect(()=>{
    console.log("New name", name)
},[name])
setName("Jane Doe")

现已修复。因此,useEffect 实际上是阻止执行,这与 Effects 完全相反。我希望你明白它的真正作用。这里有 useEffect 的正确解释。

useEffect 是一个钩子,仅当状态发生变化时才执行

我知道副作用的解释是类似的,但它就像硬币的反面
副作用解释

副作用是每当状态发生变化时执行的函数

反应系统​​中,除了Effects重新运行之外没有什么,Effects是只在状态改变时运行的函数。

React中,除了Effects重新运行之外的所有内容,Effects都是在依赖数组没有变化的情况下阻止执行的函数

最后我希望您了解 useEffect 的真正用途。上面的例子被描述为“你可能不需要效果的最差实践”。我完全明白了。但这就像他们建议我们不要使用 useEffect 作为 Effect。

大谎言

解释为

useEffect 是一个 React Hook,可让您将组件与外部系统同步。

I can't totally get it because The Phrase synchronize with external system means

The system's internal state is updated to match the state of the external system.

But in reality, useEffect had nothing to do with that. useSyncExternalStore does works in problem with some quirks ( Really this problem can't be solved 100%. For now , save that for My Another article ).

Just think about this facts that React reruns code whenever state changes and useEffect is commonly used along with React state, Then Why do we need to run something based on a state? because always reruns whenever something changes.

I found a page named as Synchronizing with Effects at React Official Docs which explains about it . At there, They explained that as

Effects let you run some code after rendering so that you can synchronize your component with some system outside of React.

From above lines, It is clear that useEffect lets you write a function which executes after rendering of React. Then WTF it is named as useEffect? Does this had any kind of connection with Effect as it's name implies? It's more similar to window.onload of DOM API.

I still can't digest the example they gave

import { useState, useRef, useEffect } from 'react';

function VideoPlayer({ src, isPlaying }) {
  const ref = useRef(null);

  if (isPlaying) {
    ref.current.play();  // Calling these while rendering isn't allowed.
  } else {
    ref.current.pause(); // Also, this crashes.
  }

  return <video ref="{ref}" src="%7Bsrc%7D" loop playsinline></video>;
}

export default function App() {
  const [isPlaying, setIsPlaying] = useState(false);
  return (
    
      <button onclick="{()"> setIsPlaying(!isPlaying)}>
        {isPlaying ? 'Pause' : 'Play'}
      </button>
      <videoplayer isplaying="{isPlaying}" src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"></videoplayer>
    >
  );
}

Here is the reason the error If You try to run it

Runtime Error
App.js: Cannot read properties of null (reading 'pause') (9:16)

   6 |   if (isPlaying) {
   7 |     ref.current.play();  // Calling these while rendering isn't allowed.
   8 |   } else {
>  9 |     ref.current.pause(); // Also, this crashes.
                       ^
  10 |   }
  11 | 
  12 |   return <video ref="{ref}" src="%7Bsrc%7D" loop playsinline></video>;

They told to us wrap it inside useEffect to solve this by

  useEffect(() => {
    if (isPlaying) {
      ref.current.play();
    } else {
      ref.current.pause();
    }
  });

because ref.current is set to null before rendering. But I could solve this by simply changed it to

 if (isPlaying) {
   ref.current?.play();
 } else {
    ref.current?.pause();
 }

If It's that what they willing to do, They it should be named as onMount like Vuejs not useEffect because effects at other library like VueJS, SolidJS really does side effect.

Here is the explanation They connected the above example with synchronisation

In this example, The “external system” you synchronized to React state was the browser media API

Does that really make any sense? I still don't know Why used synchronized here?. Here Browser Media API is available after First Render So Then Why there is a necessary of Effect here? It's a Sick Example for Effect. I never thought They would explain Effect with Example Code.

Another Joke

Effects let you specify side effects that are caused by rendering itself, rather than by a particular event.

It found this under the title What are Effects and how are they different from events? and gave above example code for this. After understanding What React really does in name of Effect and reading My Explanation, Could you connect anything?. They gave explanation of Effect of Reactivity System But They did exactly opposite. This is what I always wanted to express to Others

Final Thoughts

I hope You understand What does Effect means? and What React does in name of Effect?. After thinking All this shits, I finally decided to call useEffect
as usePreventExecution. I knew that name given by me is sick ;-) . But It is nothing when compares to What They stated about it at Official Documentation. If You found any other suitable name, Let me know at Comments.

以上是React 中的 useEffect 实际上是一个 Effect 吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python vs. JavaScript:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架:为现代网络开发提供动力JavaScript框架:为现代网络开发提供动力May 02, 2025 am 12:04 AM

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

JavaScript,C和浏览器之间的关系JavaScript,C和浏览器之间的关系May 01, 2025 am 12:06 AM

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境