On page load I want React to render a component randomly because I have two different survey forms that I want randomly assigned to a user. However, because of the multiple re-renders that react goes through the piece of code doesn’t quite work the way I expected.
Sometimes, depending on the randomness, <OpenSurvey /> will render first, then you’ll see it briefly and it will switch to <ClosedSurvey />.
How do I handle this so that my RandomlyAssignSurvey function only renders once? Do I even need the useEffect hook there?
const SurveyPage = (props) => {
useEffect( () => {
RandomlyAssignSurvey()
},[])
const RandomlyAssignSurvey = () => {
let openSurvey = "OpenSurvey"
let closedSurvey = "ClosedSurvey"
const pages = [openSurvey, closedSurvey]
let page = pages[Math.floor(Math.random() * pages.length)];
console.log(page)
if (page === "OpenSurvey") {
return (
<OpenSurvey/>
)
} else {
return (
<ClosedSurvey/>
)
}
}
return (
<SceneContainer
render={() => (
<SurveyContainer>
{RandomlyAssignSurvey()}
</SurveyContainer>
)}
/>
);
};```
Advertisement
Answer
Not sure what your render prop is doing, but an easier approach to simply rendering a random component might look like this.
const SurveyPage = () => {
return (
Date.now()%2 === 1 ? <OpenSurvey/> : <ClosedSurvey/>
);
};