I started my Own Journey with React JS as My Starter Pokemon to explore the Javascript World of Frameworks. At my First Glance, I fell for it because it reduces a lots of tons of Imperative DOM Manipulation Code. I really love the Idea of Framework automatically Manipulating DOM based on State.
At First, I didn't consider Size of React and Memory it consumes which could defeat Snorlax at Weight.
After learning React, I came across lots of Framework like Vue, Angular, Svelte. When I finally reaches SolidJS, My Eyes were opened
I started following Live Stream and Articles of Ryan Carniato, The Author of SolidJS. He totally changed the way I see Frameworks. I started understanding Reactivity Systems of Javascript Frameworks. When I turn back a bit and saw My Starter Pokemon React and It's reactivity and rendering system, I couldn't control my Laugh
It's like I was fooled from the start. Why there is a need of rerunning everything whenever a State changes? If So Then Why do we really need a hook named as useEffect to act as a side-effect.
I titled this Article as Is useEffect in React is actually an Effect? to open Your Eyes about React like Vegapunk opened eyes of People about Government ( Sorry for Spoiling to OP Fans ) . There is lots of think to criticise about it. So Today is the Day for useEffect who lied the most by hiding it's true name.
If You are the beginner or You asks some beginner at React, They would give explanation of useEffect as
A function that reruns whenever values at dependency array changes.
If You are that person, You are really lucky to knew the Truth that You are taught wrong. React reruns whenever something changes So There is not need to rerun a function because There is no need for it . Here I am going to explain the Truth about it
Let me explain what does effect is really mean. In Reactivity system, Effect is actually called as Side Effect. Let's start with an example
const name = "John Doe" createEffect(()=>{ console.log("New name", name) },[name])
Here createEffect function accepts a function which reruns whenever values in Array from second argument changes. Here function inside createEffect is a side effect of name in other words that function depends on the state name. Whenever the value of name is changed, side effect should rerun. This is what Side Effect really about.
Let me write same code in terms of React
const [name, setName] = useState("John Doe") useEffect(()=>{ console.log("New name", name) },[name]) setName("Jane Doe")
Whenever setName called, useEffect would rerun. I totally get it. Let me give equivalent code by simply removing useEffect. It also works because React's useState won't create any reactive state
const [name, setName] = useState("John Doe") console.log("New name", name) setName("Jane Doe")
TADA! It works fine in React because it reruns whenever state from useState
changes. Let me give another example to explain useEffect.
const [name, setName] = useState("John Doe") const [age, setAge] = useState(18) console.log("New name", name) setAge(21)
Now whenever age is changed, console.log("New name", name) also be executed which is not what we want. So We wrap it with useEffect.
const [name, setName] = useState("John Doe") const [age, setAge] = useState(18) useEffect(()=>{ console.log("New name", name) },[name]) setName("Jane Doe")
It is fixed now. Therefore useEffect is actually preventing the execution which is exactly opposite as Effects. I hope You understand what it really does. Here proper explaination for useEffect.
useEffect is hook that lets you executes only when there is a change in state
I knew Side Effect explanation is a similar but It's like Opposite Side of a Coin.
In explanation of Side effect
Side Effects are the functions that executes whenever there is a change in state
In Reactivity System, Nothing other than Effects reruns and Effects are the function that only runs whenever the state changes.
In React, Everything other than Effects reruns and Effects are the functions that prevents the execution without there is a change in Dependency Array
Finally I hope that You understand what useEffect really does. The Above example is stated as Worst Practice at You Might Not Need an Effect. I totally get it. But It's like They are recommending us not to use useEffect as Effect.
It is explained as
useEffect is a React Hook that lets you synchronize a component with an external system.
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.
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
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.
The above is the detailed content of Is useEffect in React is actually an Effect?. For more information, please follow other related articles on the PHP Chinese website!