Home > Software design >  React : how to prevent the hidden component from appearing during rendering?
React : how to prevent the hidden component from appearing during rendering?

Time:07-21

During rendering of the part below, the component CreateGarden appears for 1 sec even if the condition is true.

  {userInfo.gardenName ?
    <ShowPlants />
    :
    <CreateGarden setModal={setModal} />
  }

Here is the custom hook I use to get userInfo

export default function useUserInfo() {
    const [userInfo, setUserInfo] = useState([]);
    const [categories, setCategories]= useState([]);

    const userRef = doc(allUsers,auth.currentUser.uid);

    useEffect(() => {  
       const unsub = onSnapshot(userRef, (doc)=>{
         setUserInfo(doc.data())
         setCategories(doc.data().categories)
         }) 

         return ()=>unsub()
      },[auth.currentUser]);

    return {userInfo, categories};
}

I tried creating loading state in the hook and use it as additional condition to render but it's still the same , I keep having a glimpse of the hidden component.

CodePudding user response:

You could display a loading icon while the data is being fetched.

When

  1. data hasn't been fetched yet (undefined) -> show loading icon (your hook could return a loading value as well as an error value in case something went wrong)
  2. data has been fetched and there is a gardenName, display ShowPlants
  3. data has been fetched and there is no gardenName, display CreateGarden

CodePudding user response:

What if you use them separately?

{ userInfo.gardenName && <ShowPlants /> }

{ !userInfo.gardenName && <CreateGarden setModal={setModal} /> }
  • Related