'React memo get magically executed twice [duplicate]
i'm creating a react app with useMemo
.
The memo uses empty array as the dependency list, so it should be executed once, right?
Inside the memo, there are console.log()
& counter++
to visualize how many times the memo get executed.
Magically, I got one log but the counter seems executed twice.
See this sandbox or see the code below:
import {
useMemo,
} from 'react'
let counter = 0;
export default function App() {
const foo = useMemo(() => {
console.log('increase counter');
counter++;
}, []);
return (
<p>
{counter}
</p>
);
}
Solution 1:[1]
It looks like you're incorrectly using useMemo
A useMemo()
computes something only when something in its dependancy array changes. It looks like you haven't given the dependancy array any variables.
Please review this example of useMemo
:
export default function App() {
const [loading, setLoading] = useState(true);
const component = useMemo(() => {
if(loading){
return <div>Loading...</div>
} else {
return <div>Finished Loading</div>
}, [loading]);
return (
<div>
{component}
</div>
);
}
As you can see from this example when the state changes the useMemo is computed.
In your above example, I imagine the useMemo is being computed twice because its happening each time the page renders.
For your counter example I would recommend just using useState.
export default function App() {
const [counter, setCounter] = useState(0);
return (
<div>
<p>{counter}</p>
<button onClick={() => setCounter(prevState => prevState++)}>Increase Counter</button>
</div>
);
}
EDIT: This question was actually resolved in the comments. Disabling StrictMode prevents the double re-render.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |