search
HomeWeb Front-endJS TutorialIs useEffect in React is actually an Effect?

React : I Choose You

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.

Is useEffect in React is actually an Effect?

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

Is useEffect in React is actually an Effect?

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

Is useEffect in React is actually an Effect?

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.

Now Get into the Title of Article

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

What does Effect really mean?

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.

What React actually does?

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.

Big Lie

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="%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.

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software