Utilizing the change of state in one useEffect to prompt the execution of another useEffect

While working on a project, I decided to incorporate a wysiwyg style editor. I came across a video on YouTube showcasing a Reddit clone that had the feature integrated using Editor JS. As I delved into the code, I noticed an interesting use of useEffect triggering another useEffect, which left me a bit puzzled.

  useEffect(() => {
    if (typeof window !== 'undefined') {
      setIsMounted(true)
    }
  }, [])

  useEffect(() => {
    const init = async () => {
      await initializeEditor()

      setTimeout(() => {
        _titleRef?.current?.focus()
      }, 0)
    }

    if (isMounted) {
      init()

      return () => {
        ref.current?.destroy()
        ref.current = undefined
      }
    }
  }, [isMounted, initializeEditor])

The creator used the first useEffect to trigger the second one. This raised some doubts in my mind - why didn't they initialize the editor in the initial effect itself? So, I tried replicating the same approach:

useEffect(() => {

    const init = async () => {
      await initializeEditor()
    }

    if (typeof window !== 'undefined') {
      init()
    }
  }, [])

However, this led to the editor being initialized twice for me. The issue was resolved by disabling strict mode. This made me wonder why the editor wasn't initialized twice in the original example?

Answer №1

One reason for this behavior is that the useEffect function runs twice when the component mounts in development and strict mode

In the second code example, the initializeEditor function will be executed twice because the useEffect is triggered twice.

However, in the first code example, even though the second useEffect also runs twice on mount, the intializeEditor function is not called at all initially because the value of isMounted is false.

Once isMounted changes to true due to the execution of setIsMounted(true) in the first useEffect, the second useEffect only runs once since its dependency, isMounted, has changed. This results in the initializeEditor function being called only once.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to efficiently pre-load data using the prefetchQuery method in React-Query

Attempting to pre-fetch data using react-query with prefetchQuery. The network tab in browser DevTools shows the requested data coming from the back-end, but strangely, the data is not present in the react-query DevTools cache. Any ideas on what might be c ...

When a user clicks on the datepicker, I want to trigger a change in the

I am working on a Flight API and I need to implement functionality where when the user clicks on the return journey field, the button toggles from single trip to round trip (false to true). <DatePicker hintText="Return Date" errorText={this.state.j ...

Modifying JSON data in a React Application - Innovative Page Building Idea

Creating a page builder that allows users to drag and drop elements onto a screen, resulting in a config JSON object that needs to be saved in a config.json file. The goal is to have live reload functionality while editing pages using this builder. The fr ...

Struggling with connecting or executing queries in getStaticPaths/getStaticProps while incorporating Snowflake into NextJS

After spending some time experimenting with NextJS, I decided to take on the challenge of converting an application into prerender static pages using getStaticProps and getStaticPaths with [id].js files for each page organized in their individual folders ( ...

Is the examples folder missing from the repository after installing react-router using npm?

After executing the npm install react-router command, it installs version react-router v1.0.3 which includes an examples directory. However, when running the commands: cd node_modules/react-router ls The resulting output is: CHANGES.md README.m ...

Encountering 'no overload matches this call' while developing a useReducer using React with Typescript

import { useCallback, useReducer } from "react"; const ARTIST_REDUCER_TYPES = { ADD: "ADD", }; const artistArray = [...Object.values(ARTIST_REDUCER_TYPES)] as const; type ActionReturnedTypes = (typeof artistArray)[number]; type Re ...

Display solely the error message contained within the error object when utilizing the fetch API in JavaScript

I am facing an issue in logging the error message to the console while everything else seems to be working fine. Specifically, I am unable to log only the message such as "email exists" when the email already exists in the system. const submitHandler = a ...

Updating state on nested arrays in React components involves using the `

UPDATE** Currently, the structure of my React state is as follows: this.state = { data: { groups: [[]] }, preview: [[]] } Each element in groups is an array that contains files. I have a file change event handler that currently looks ...

Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component. To achieve this, I have detailed the following instructions in the interface ...

Deciphering the sequential process of decision-making within a react-redux application

I'm seeking to comprehend the flow of an application in a react-redux setup specifically when it comes to logging in. Within the redux state of the application, there exists a boolean variable named loggedIn which starts off as false. When the value ...

Unauthorized clerk authentication request causing a 401 error on http://localhost:3000/. There seems to be a continuous loop of 401 errors occurring after signing in and out

Hello, I have been attempting to set up Clerk on the latest version of Next using the app router. After carefully reading through the documentation, I found the setup process straightforward and decided to give it a try on a new project I've been wo ...

Can you guide me in utilizing this API endpoint efficiently to enable search functionality using React Query?

const { isLoading, isError, data, error, refetch } = useQuery( "college", async () => { const { result } = await axios( "http://colleges.hipolabs.com/search?name=middle" ); console.log(&quo ...

The issue with the antd Input component's onChange event not updating state correctly when using a list fetched from an axios get request in a React

Recently delving into React, I've dedicated the past week to honing my skills. My current project involves creating a straightforward application featuring a 'product create' form alongside a product list equipped with a search bar (utilizin ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Struggling to successfully upload a file using express and fileupload, but I am having trouble getting it to function properly

This is my first attempt at uploading files to the server, following a tutorial to build both frontend and backend in React. Unfortunately, I'm facing some difficulties getting it to work properly. I've made adjustments to my backend and tested ...

Implementing location functionality in Nextjs 13+ for both server-side rendering and client-side components

I need help displaying an active link in the header navigation. Previously, I used useRoute() for versions under 13, but it stopped working in version 13 and above. Additionally, useRoute is not mounted when using SSR. To work around this issue, I ensured ...

How to integrate the BackButton component into a React-admin application

I am looking to add a <BackButton /> feature in my use of react-admin. For instance, when viewing a show page for a resource, I want to be able to navigate back to the list page easily. Can someone provide me with guidance on how to achieve this? I ...

Creating a registration and authentication system using firebase

When using Google authentication with Firebase, is the Signup and Login logic the same? I am creating a page for user authentication but I'm unsure if I should have separate pages for signing up and logging in. This confusion arises from the fact that ...

Having trouble with incorporating RBAC in React, facing issues with page rendering post successful login

Struggling to incorporate RBAC into my React application, I have a backend in Node.js that is working well, and for the frontend I'm using Vite and React Router DOM v6. To keep things simple, I decided to store the token and role received from the ser ...

Developing the headers for a service using React.js

As someone new to ReactJs, I'm curious about the various methods we can use to include Headers in our service Url before making a call. While I'm familiar with how GET/POST Calls are made in angular Js after including headers, I'd like to l ...