Skip to main content

Command Palette

Search for a command to run...

React bad setState() call

Published
2 min readView as Markdown
React bad setState() call
N

Hi there! My name is Nidhi sharma and I am a frontend developer currently working as an intern. I have a strong passion for creating user-friendly and visually appealing websites and applications, and I am always looking to learn and improve my skills.

As a frontend developer, I use a variety of programming languages and tools, such as HTML, CSS, and JavaScript, React, to bring my designs to life and make them interactive and responsive.

I am excited to have the opportunity to learn from and contribute to a team of experienced developers. I am eager to take on new challenges and to apply my skills and knowledge to real-world projects.

Warning: Cannot update a component (`App`) while rendering a different component (`Testing`). To locate the bad setState() call inside Testing, follow the stack trace as described

Here, if you click on the showModal button, you’ll see the warning.

Warning: Cannot update a component (App`) while rendering a different component (`Testing`). To locate the bad setState() call inside Testing, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at
Testing (https://26chx4.csb.app/src/testing.js:13:30)
at
at) div
at App (
https://26chx4.csb.app/src/App.js:16:41)

To fix this error all you need to do is move the useMemo to the parent component or change it to useEffect so that it will run after the component mount

import { useMemo } from "react";

const Testing = ({ setTestingState }) => {

  useMemo(() => {
    setTestingState(false);
  }, [setTestingState]);

  return <h1>Testing</h1>;
};

export default Testing;

Here the main culprit is

useMemo(() => {
    setTestingState(false);
  }, [setTestingState]);

so either change it to this

useEffect(() => {
    setTestingState(false);
  }, [setTestingState]);

show that it runs after the component mount or move the code to parent component

// APP.JSX

import { useState, useMemo } from "react";
import Testing from "./testing";

function App() {
  const [showModal, setShowModal] = useState(false);
  const [testingState, setTestingState] = useState(false);
  useMemo(() => {
    setTestingState(false);
  }, [setTestingState]);
  return (
    <div>
      <h1>This is app</h1>
      <button onClick={() => setShowModal(true)}>Show Modal</button>
      {showModal ? <Testing setTestingState={setTestingState} /> : null}
    </div>
  );
}

export default App;

// Testing.jsx
const Testing = () => {
  return <h1>Testing</h1>;
};

export default Testing;

That’s all you have to do.

I hope you find it helpful.

Happy coding!

want to give suggestions:-

find me on LinkedIn Twitter

Email me at nidhisharma639593@gmail.com