I keep bumping into this problem in different scenarios where I want to render a component conditionally and the state is not set immediately thus the component I want to render is momentarily shown after a "flicker" of the other component in my conditional logic.
In the code below I have a useContext instance and I have a Boolean assigned to context.state.clientsExist
. Depending on the state of this Boolean I want to show one of two components.
The problem is that the component in the "else" branch flickers momentarily. This is because const [clients_exist_bool, set_clients_exist_bool] = useState(false);
does not get set immediately.
I tried a few ways to hide this with a loader and I can't get it right.
function Landing(props){
const [loading_bool, set_loading_bool] = useState(true);
const [clients_exist_bool, set_clients_exist_bool] = useState(false);
const context = useContext(Context);
useEffect(()=>{
let clientsExist = context.state.clientsExist;
set_clients_exist_bool(()=>{
if(clientsExist){
return true
}
})
},[context.state.clientsExist])
const { classes } = props;
// render loader...? I tried and still flickers.
if(clients_exist_bool){
return (
<div className = {classes.bgImage}>
<div className={classes.root}>
<Grid container spacing={12}>
<Grid item xs={12}>
</Grid>
<Grid item xs={12} sm={12}>
</Grid>
<Grid item xs={12} sm={12}>
<div className={classes.interactionContainer}>
<h1 className="logoFontContainer">
Workflow Magic
</h1>
</div>
</Grid>
</Grid>
<CreateClients/> {/* MOVE UP */}
</div>
</div>
)
}else{
return(
<div className = {classes.bgImage}>
<div className={classes.root}>
<Grid container spacing={12}>
<Grid item xs={12}>
</Grid>
<Grid item xs={12} sm={12}>
</Grid>
<Grid item xs={12} sm={12}>
<div className={classes.interactionContainer}>
<h1 className="logoFontContainer">
Workflow Magic
</h1>
<h2 className={classes.tagline}>The simple way to organize your online gigs</h2>
<a className={classes.customAnchor}href="/sign-in">
<h3 className={classes.signInSignUp}>SignIn / SignUp</h3></a>
<p className={classes.signInSignUpNoHover}>NO?</p>
<h3 className={classes.signInSignUpNoHover}>THEN GET STARTED NOW!</h3>
</div>
</Grid>
</Grid>
<CreateClients/>
</div>
</div>
)
}
}