DEV Community

Discussion on: 4 Ways to Render JSX Conditionally in React

 
joelbonetr profile image
JoelBonetR 🥇

Adding that it depends on the architecture of the frontend in this case.
When I do a "standard React SPA" I barely use this early return, but having Next JS with SSR and a headless CMS as source of structure/data makes it almost mandatory. In this last case there's a builder which receives a big JSON from a micro which defines which components will show up on a given view through a dynamic component loader process.

We cannot ensure the structure and/or content inside the CMS to be reliable as it's human made, and during those months it has been proved that human errors could appear.

I agree on that

Both have the problem that you're optionally calling hooks, so both are going against the rules of hooks.

generally speaking, but not in this context.
As it's Server Side Rendered, it will not magically get the data afterwards through an async process or whatever. The structure and data you receive into the JS is the "director" about what and how will be shown, and what you actually handle in the view is the pre-rendered in which you can safely use this early return to avoid further execution of that piece of software.

you can use a Node API and/or handle requests to third parties or other micros in the server context (getServerSideProps) but you can need, eventually, to add an async call to get data from a micro or third party to search or filter.
Then you have two options, either reload the view adding query params or whatever, handling it in the Node JS context to keep it full-SSRed, or do the async thingy (fetch) in the frontend, in which case I'd recommend a loader/spinner, then the conditional render will look like that:

return loading ? <Loader /> : <DataTable data={fetchedData} />
Enter fullscreen mode Exit fullscreen mode

and you'll never return null nor undefined because there's no sense on it.