skip to Main Content
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


  1. The log is printed 2 times, because:

    • the component is rendered the first time
    • all useEffects are called, including the setBoolValue() and the console.log()
    • because the booValue has changed, the component is rendered again
    • the useEffects are called a second time, this time only the console.log() is executed (because it depends on booValue).

    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 on booValue in the useEffect", 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search