console.log printing multiple times despite outside useEffect
Answered
Gecco posted this in #help-forum
GeccoOP
In this code my console.logs are printing each time
phraseUpdate is triggered and I'm not sure why since they're outside the function itself. Could anyone explain to me what is happening? For reference strict mode is offconst phrases = ["JavaScript Developer", "Backend Nerd"];
const phraseUpdate = () => {
setPhrase(phrases[0]);
phrases.push(phrases[0]);
phrases.shift();
setTimeout(phraseUpdate, 3000);
};
useEffect(() => {
phraseUpdate();
}, []);Answered by joulev
The console.log is run every render. So whenever your component rerenders, the log is run. When you run phraseUpdate(), it updates the phrases state, which forces a rerender of the component
5 Replies
I don’t see any console logs in the snippet you posted
@joulev I don’t see any console logs in the snippet you posted
GeccoOP
my bad, here is a more full version
export default function Home() {
const [phrase, setPhrase] = useState("");
const headingP = useRef(null);
console.log(headingP);
console.log("test");
const phrases = ["JavaScript Developer", "Backend Nerd"];
const phraseUpdate = () => {
setPhrase(phrases[0]);
phrases.push(phrases[0]);
phrases.shift();
setTimeout(phraseUpdate, 3000);
};
useEffect(() => {
phraseUpdate();
}, []);@Gecco my bad, here is a more full version
ts
export default function Home() {
const [phrase, setPhrase] = useState("");
const headingP = useRef(null);
console.log(headingP);
console.log("test");
const phrases = ["JavaScript Developer", "Backend Nerd"];
const phraseUpdate = () => {
setPhrase(phrases[0]);
phrases.push(phrases[0]);
phrases.shift();
setTimeout(phraseUpdate, 3000);
};
useEffect(() => {
phraseUpdate();
}, []);
The console.log is run every render. So whenever your component rerenders, the log is run. When you run phraseUpdate(), it updates the phrases state, which forces a rerender of the component
Answer
GeccoOP
Is there a way to prevent such? or is that just the nature of Next/React?
@Gecco Is there a way to prevent such? or is that just the nature of Next/React?
That’s just how react works.
function Hello() {
console.log("rendered")
const [x, setX] = useState(0)
return <button onClick={() => setX(x => x+1)}>Click me</button>
}