import React from "react";
export default function TestComponent(){
const [booValue, setBoolValue] = React.useState(false)
React.useEffect(() => {
setBoolValue(!booValue);
},[])
React.useEffect(() => {
console.log('booValue is', booValue)
},[booValue])
return (
<></>
)
}
What to do not to print twice. Its not in StrictMode
boolValue is false
boolValue is true
tried default value as undefined, i assume that useEffect
triggers on setting default values. tried with null values too.
2
Answers
The log is printed 2 times, because:
useEffect
s are called, including thesetBoolValue()
and theconsole.log()
booValue
has changed, the component is rendered againuseEffect
s are called a second time, this time only theconsole.log()
is executed (because it depends onbooValue
).Your actual question "What to do not to print twice" can not be answered reasonably, because your code does effectively nothing apart from printing twice.
E.g. an answer could be "remove the call to
setBoolValue()
", or "remove the dependency onbooValue
in theuseEffect
", but I’m sure you wouldn’t like such an answer, as your code is surely simplified to demonstrate the problem, (which is great that you have done that), but in this case the actual problem lies somewhere else.If you have such a problem, you need to understand that you should not rely on a
useEffect
to be called a certain amount of times.I suggest to read You Might Not Need an Effect.
follow the documentation
Description here
Description here