React bad setState() call

Nidhisharma
2 min readFeb 14, 2023

--

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

Photo by Tianyi Ma on Unsplash

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 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

--

--

Nidhisharma
Nidhisharma

Written by Nidhisharma

Self-taught front-end web developer! Js | React.js | Git. Find me on LinkedIn: https://shorturl.at/oTX04 open to work

No responses yet