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)

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

JavaScript的最新趋势包括TypeScript的崛起、现代框架和库的流行以及WebAssembly的应用。未来前景涵盖更强大的类型系统、服务器端JavaScript的发展、人工智能和机器学习的扩展以及物联网和边缘计算的潜力。

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

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

JavaScript是现代Web开发的核心语言,因其多样性和灵活性而广泛应用。1)前端开发:通过DOM操作和现代框架(如React、Vue.js、Angular)构建动态网页和单页面应用。2)服务器端开发:Node.js利用非阻塞I/O模型处理高并发和实时应用。3)移动和桌面应用开发:通过ReactNative和Electron实现跨平台开发,提高开发效率。

本文展示了与许可证确保的后端的前端集成,并使用Next.js构建功能性Edtech SaaS应用程序。 前端获取用户权限以控制UI的可见性并确保API要求遵守角色库

我使用您的日常技术工具构建了功能性的多租户SaaS应用程序(一个Edtech应用程序),您可以做同样的事情。 首先,什么是多租户SaaS应用程序? 多租户SaaS应用程序可让您从唱歌中为多个客户提供服务

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