React 中的 useEffect 实际上是一个 Effect 吗?
反应:我选择你
我开始了我自己的 React JS 之旅,作为我的入门 Pokemon 来探索 Javascript 框架世界。乍一看,我爱上了它,因为它减少了大量命令式 DOM 操作代码。我真的很喜欢框架根据状态自动操作 DOM 的想法。
一开始,我没有考虑 React 的大小和它消耗的内存,这可以在重量上击败 Snorlax。
学习 React 后,我接触到了很多框架,比如 Vue、Angular、Svelte。当我终于接触到 SolidJS 时,我的眼睛睁开了
我开始关注 SolidJS 的作者 Ryan Carniato 的直播和文章。他完全改变了我看待框架的方式。我开始了解 Javascript 框架的反应系统。当我回头看到 My Starter Pokemon React 及其反应性和渲染系统时,我无法控制自己的笑
好像我从一开始就被愚弄了。为什么每当状态发生变化时都需要重新运行一切?如果是这样那么为什么我们真的需要一个名为 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={src} loop playsInline />; } 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" /> </> ); }
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={src} loop playsInline />;
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中文网其他相关文章!

热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。
