Home > database >  Change or Create a component with hooks
Change or Create a component with hooks

Time:11-28

I'm learning react and I'm still confused about the way we have to build and modify components. I'm working on the UI registration part of my project and I want a specific component in the case where the user is actually registred or not.

I have created a boolean attribute in each of this case using useState and from what I've read, I've got a useEffect to allow me to check the latest status of my first hook. So if it's true it means the user is well created in DB, from this I want to create (or modify) a component which will be telling to the user if he is well registred on the app.

const [signinStatus, setsigninStatus] = useState(false);

useEffect( () => { 
  if (signinStatus === true) {
    console.log(signinStatus);}
  
}, [signinStatus]);

Can I create or modify a component inside my useEffect hook or am I going in the wrong direction?

CodePudding user response:

you could use signinStatus value directly and conditional rendering together for this goal. there is no need to modify anything in useEffect.

const [signinStatus, setsigninStatus] = useState(false);


return <>

   {
       sigingStatus ? <SomeComponent/> : <AnotherComponent/>
   }

</>

CodePudding user response:

useState : This keeps some data & helps in re-rendering. Whenever it changes, component rerenders.

useEffect : This is the function that is called when component is initially rendered or any of the dependency provided in the second parameter in the function changes.


What you can do is

function LoginUser(){
   const [signinStatus, setsigninStatus] = useState(false);

   useEffect( () => { 
     if (signinStatus === true) {
        console.log(signinStatus);}
   }, [signinStatus]);

   return <div>{signinStatus===true ? <p>User is logged in</p> : <p>User is not logged in</p>}</div>
}
  • Related