React bad setState() call

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 reactjs.org/link/setstate-in-render
at
Testing (26chx4.csb.app/src/testing.js:13:30)
at
at) div
at App (
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