Home > Net >  would using useState(undefined) for boolean state instead of useState(false\true) considered ok?
would using useState(undefined) for boolean state instead of useState(false\true) considered ok?

Time:09-27

I am writing my program and I see almost everywhere, that the starting useState() condition is false: "useState(false)", when we are working with booleans.

But can I leave it empty (useState()), instead of defining it as false? In my example, I am defining 3 states for error messages:

  const [isErrorInName, setIsErrorInName] = useState();
  const [isErrorInEmail, setIsErrorInEmail] = useState();
  const [isErrorInMessage, setIsErrorInMessage] = useState();

And below I use useEffect hook:

  useEffect(() => {
   if (
     isErrorInName === false &&
     isErrorInEmail === false &&
     isErrorInMessage === false
   ) {
        document.getElementById("contact-form").reset();
     }
   }, [isErrorInName, isErrorInEmail, isErrorInMessage]);

And because of this hook I can't define these useState() conditions as false, because then the form will be reseted, when the app will start, because this is what useEffect hook does. But if I leave them as undefined, everything is working.

Thanks!

CodePudding user response:

First of all, AFAIK there isn't a problem with an empty useState, so it is something you can do.
If, on the other hand, you do want it to contain an initial value, it's possible to detect first render in a few ways, like this one, where a ref is being used solely for this purpose.

P.S. - would recommend to conjoin states like these into objects to prevent pointless re-renders.
Especially useful when you are dealing with a bunch of different state pieces.

i.e:

const [errors, setErrors] = useState({
   isErrorInName: false,
   isErrorInEmail: false,
   isErrorInMessage: false,
})

CodePudding user response:

You most certainly can. However, for these types of situations, I usually prefer to set the initial value to null.

This has a couple of advantages, for instance, you can define the type for your hooks (i.e: useState<boolean>(null) is very much ok) and you can check whether it has been set or not using === null and you can reset it back to null if you need to reuse this check.

I also agree with @tomleb3 's answer. Flattening them into one state will make sure you don't get multiple rerenders.

CodePudding user response:

Yes you can.

Also, instead, you can also add the state isPrestine, to indicate no input is entered:

const [isPrestine, setIsFormPrestine] = useState(true);

That way, each variable represents a single thing, which might improve code in the long run.

  const [isErrorInName, setIsErrorInName] = useState(false);
  const [isErrorInEmail, setIsErrorInEmail] = useState(false);
  // and so forth

  if (
 ! isPrestine &&
 ! isErrorInName &&
 ! isErrorInEmail &&
 ! isErrorInMessage 
  )
  • Related