Rendering react elements with ifs, ternaries, switches, or object properties - a podcast by Kent C. Dodds

from 2021-03-30T16:48:35

:: ::

Hey there friends. So today I'm going to answer a question from Lean or
Leon I'm not sure how to say your name sorry but this is asked in the react
hooks channel of the discord the KCD discord under the Epic Reactivecategory and it's talking about exercise six where we show it's it's an
exercise on managing state for asynchrony, so we've got to use effect in
there and stuff.And we have this status status and that is the status of the promise. So
whether it's idle pending reject,Ed or resolved and we render different
things based on that. And in my solution, I just do an if statement. So ifstatus is idle, then this outsift status is pending then render this also
status is rejected then do this.And that I I was pretty happy with that. But I there are obviously several
different ways to do this and one natural thing that people sometimes willdo is a switch statement which is what this individual suggested why don't
we do the switch statement, but then they got some pushback on that.Hat from a co-worker. I think that suggested using an object instead and so
you can say here's a a object that has the status value so you have idle
pending rejected results and each one of those is assigned a as a propertythe the value is going to be the react element that should be rendered.
So I mentioned that I would talk about this. So in the next version of EpicReact, so if you look in this repo on the next branch, I actually switched
to not only TypeScript.And but I also switched to using a switch statementJust because I think that it makes a little bit more sense in this context.
Like I said, I often don't use switch statements. I prefer if else or maybe
even ternaries but in this case, it just seemed to look a little cleanerand so I use the switch statement there. Definitely know hard and fast rule
on that. It's just try them both and pick the one that you dislike the
least.Um, but I did mention in this discord chat that it actually is really not a
good idea to use the object approach for something like this. And thereason is that,Sometimes you're gonna be switching on something like in our
case we're displaying a Pokemon. And if you're going to create React
Elements that reference properties of that Pokemon then you you're going to
be accessing properties that may not exist based on the status like if youhave idle the Pokemon could be null.
And so if you're even though those different properties of that object
won't actually get rendered you do have to access those properties to
create the React elements. So, that's why you don't want to use the object
form in this case at all. So, I hopeThat's useful and interesting and I
hope you have an awesome day.Goodbye.

Further episodes of 3 Minutes with Kent

Further podcasts by Kent C. Dodds

Website of Kent C. Dodds