Stop Conditional Rendering in React Without Knowing This (&& vs Ternary Operator)

Поделиться
HTML-код
  • Опубликовано: 2 июн 2024
  • 👉 NEW React & Next.js Course: bytegrad.com/courses/professi...
    Hi, I'm Wesley. I'm a brand ambassador for Kinde (paid sponsorship).
    👉 Add authentication to your app FAST: bit.ly/3QOe1Bh
    👉 NEW React & Next.js Course: bytegrad.com/courses/professi...
    👉 Professional JavaScript Course: bytegrad.com/courses/professi...
    👉 Professional CSS Course: bytegrad.com/courses/professi...
    👉 Discord: all my courses have a private Discord where I actively participate
    🔔 Email newsletter (BIG update soon): email.bytegrad.com
    ⏱️ Timestamps:
    0:00 Ternary operator
    0:42 && operator
    1:08 Beginner mistake
    2:13 Solution 1
    2:28 Better solution
    3:03 Best solution
    3:28 Junior mistake
    3:50 Important!
    #webdevelopment #programming #coding

Комментарии • 95

  • @ByteGrad
    @ByteGrad  3 месяца назад

    My Professional React & Next.js course is OUT NOW now! Find it here: bytegrad.com/courses/professional-react-nextjs -- this is the #1 resource to master the latest React & Next.js, my absolute best work.

  • @curiouslycory
    @curiouslycory 9 месяцев назад +29

    Ternary operators are great if you're only dealing with one or two lines, but when they're used to conditionalize big blocks of output they immediately become really hard to read. I avoid nested ternary for the same reason. Good code isn't just bug free and performant, it is maintainable and extensible as well.

    • @YuretsUA
      @YuretsUA 6 месяцев назад

      I saw such code with two or even three nested ternar operators, it's really ugly and hard to read, double ! it's a way more easier to read.

    • @austincodes
      @austincodes 3 месяца назад +1

      I 100% agree. It's almost always better to break the code up into smaller components and use an early return inside of an if statement

  • @MrPlaiedes
    @MrPlaiedes 8 месяцев назад +10

    As a lead dev, I recommend creating derived variables like hasProducts that handles the logic (ie products.length > 0) so that you're not cluttering up your render. I'd also recommend limiting the usage of ternarys. And if you're nesting them, it may be time to factor your component.

    • @ByteGrad
      @ByteGrad  8 месяцев назад +1

      Good tips, thanks for sharing

    • @luar4165
      @luar4165 8 месяцев назад

      could you expand your point (for a beginner like me) , please? do you mean creating a boolean variable `const hasProducts = true` if products.length > 0 ? and then use it in the conditional rendering? . Thanks in advance

    • @davidchavez4054
      @davidchavez4054 8 месяцев назад +4

      OP recommends creating a variable like const hasProducts = Boolean(list.length). The idea is you avoid both, printing a 0 om screen and cluttering the jsx with extra logic

  • @yichern4351
    @yichern4351 10 месяцев назад +14

    I've just recently come across your channel and I love the content that you create. The explanations are straight-to-the-point and easy to understand, and the topics are practical and useful. Thanks very much!

    • @ByteGrad
      @ByteGrad  10 месяцев назад +2

      Appreciate it, that’s exactly my goal. Thanks 😊

  • @jitx2797
    @jitx2797 10 месяцев назад +4

    Wow. Your way of presentation and teaching is so much better. You make us aware about the possible problem that could occur and how to fix. Watched your clsx video too and it was awesome.
    Thanks for making these videos. Keep making these.

    • @ByteGrad
      @ByteGrad  10 месяцев назад

      Thanks, will do 😃

  • @TheGrandChieftain
    @TheGrandChieftain 9 месяцев назад +4

    Using the && operator is just harder to read for me, glad I avoided it, never have to worry about these edge cases.

  • @andreypetrovskiy7056
    @andreypetrovskiy7056 9 месяцев назад +7

    For better readability of conditionals, you can add something like Show wrapper component:
    function Show({ when, fallback = null, children }) {
    return when ? children : fallback
    }
    it will also solve the problem of having to convert to boolean, since you always have a ternary with default null as 'else' part
    Products in stock

    • @ByteGrad
      @ByteGrad  9 месяцев назад

      Interesting point

    • @creatorsremose
      @creatorsremose 8 месяцев назад +7

      The definition of unnecessary complexity.

  • @Bateleur90
    @Bateleur90 9 месяцев назад +1

    Awesome insight! Any way to have a warning with eslint, when you are using && with a value that could be 0 or NaN?

  • @insanity7538
    @insanity7538 8 месяцев назад

    Another approach is to use ifs and early-return style to explicitly render null. I think it's much easier to read than either of the approaches shown in your video.

  • @VeniMitev
    @VeniMitev 10 месяцев назад +3

    Beginning of my career, I had a lot of random 0s pop up around the apps 😂 When I found this out I made a pretty big pull request fixing all these issues...

    • @ByteGrad
      @ByteGrad  10 месяцев назад

      Haha yeah it happens

  • @roby_codes
    @roby_codes 9 месяцев назад +1

    Every video I watch from you I find myself doing such mistakes in my code without ever realizing it 😂

  • @FIash911
    @FIash911 9 месяцев назад +2

    i prefer to use 'smth ?? fallback' instead of 'smth ? fallback : null' which does the same thing, but much shorter

    • @veedjohnson
      @veedjohnson 9 месяцев назад

      This wouldn’t work in the case of the array.length
      The ?? Operator only checks for null and undefined values so if array.length returns 0, the operator wouldn’t be able to catch that

  • @DevvOscar
    @DevvOscar 10 месяцев назад +14

    This has to do with truthy and falsely. Stupid how JavaScript works. I don’t like ternaries in my JSX. It obfuscated so much. I always try to use an early return.

    • @ByteGrad
      @ByteGrad  10 месяцев назад +1

      Yep, it’s JSX not JS. I agree, ternaries clutter up JSX too much

    • @DevvOscar
      @DevvOscar 10 месяцев назад +1

      ​ @ByteGrad Yeah but everything within {} is evaluated as Javascript. Didn't mean to bite down. I like your content. I learned some new hooks from your channel.

    • @ByteGrad
      @ByteGrad  10 месяцев назад +1

      True but if you put undefined, null, empty string etc in the curly braces JSX won’t output that on the page, however it will output 0 and NaN. That’s confusing
      Edit: no problem mate

  • @dustyhordofelbamana279
    @dustyhordofelbamana279 9 месяцев назад +1

    Hi Wesley, your nextjs course isn't available yet? i've already taken your javascript course, your Nextjs cour isn't available yet? i've already taken your javascript course. Thanks !

    • @ByteGrad
      @ByteGrad  9 месяцев назад

      Hi, it’s almost finished. Make sure you’re on the email list :)

  • @mu_yaser
    @mu_yaser 10 месяцев назад +1

    looks like i just found a promising channel. like your vid mate

    • @ByteGrad
      @ByteGrad  10 месяцев назад

      Awesome, thank you!

  • @y7o4ka
    @y7o4ka 9 месяцев назад +5

    I'm pretty sure that in the first case it has nothing to do with JSX. It simply converts the 0 to a string "0" and outputs that. Many developers thing that (0 && 1) will return false, but && will short-circuit to the first falsey value (in this case 0), not false:
    {0&&1}
    {0}
    0
    Edit: i fucked up the closing tags, that's what i get for commenting code on a phone

    • @anonymoussloth6687
      @anonymoussloth6687 8 месяцев назад

      Can u elaborate? I still don't get what 0 && 1 means. It won't give a bool?

    • @y7o4ka
      @y7o4ka 8 месяцев назад +1

      @@anonymoussloth6687 no it won't. *&&* will return the first value if it's truthy, else the second value. So a && b should be equivalent to something like a ? a : b

    • @y7o4ka
      @y7o4ka 8 месяцев назад

      However, what JSX does is it omits null, undefined, etc. from the render. So, if in a && b a is truthy and b is undefined, && will evaluate to undefined, but JSX will render this undefined as an "" rather than "undefined". This is useful, yes, but not very consistent and can be misleading for new devs, hence why you shouldn't rely on implicity

    • @anonymoussloth6687
      @anonymoussloth6687 8 месяцев назад

      @@y7o4ka oh. But then ur saying in js, if there is a if state like if(a && b) this doesn't give a bool, it gives either a or b depending on their truthy-ness? Suppose a was falsy, it wouldn't give false but rather the value of a itself?

    • @y7o4ka
      @y7o4ka 8 месяцев назад +1

      @@anonymoussloth6687 Exactly. Open a browser console or launch node and enter something like `"truthy" && "hello!"` or `undefined && "bye :("`. You should see "truthy" and then `undefined`. Then `if` will see whatever && evaluated to.
      So if("truthy" && "hello!") will evaluate to if("hello!"). If will see that "hello!" is truthy and enter the block

  • @dechobarca
    @dechobarca 9 месяцев назад +1

    Awesomely explained, keep up the good work!

  • @mskzzz
    @mskzzz 9 месяцев назад +4

    I really dislike the ternary returning null if false, it delays the understanding of what is happening when you read the code. With && you already know that this will only be displayed if the condition is true.
    As for the condition, I personally prefer explicit conditions like array.length > 0, even though !!array.length is something quite common, it's just faster for the brain to process array.length > 0 as it is closer to the reality

    • @monome9992
      @monome9992 9 месяцев назад +1

      Clearly the most valuable comment ! Explicit condition is usefull for maintanability and readability

    • @Adam-nw1vy
      @Adam-nw1vy 9 месяцев назад +1

      @@monome9992 I totally agree. The more explicit, the better. Using `!!` is kinda tricky and could trip up someone.

    • @a_maxed_out_handle_of_30_chars
      @a_maxed_out_handle_of_30_chars 7 месяцев назад +1

      true, even though I know what !! does it still takes time to figure it out so length > 0 is easy to process

  • @ELMlKO
    @ELMlKO 9 месяцев назад +3

    what about the ?? operator does it not help?

  • @mohamedyoussef8835
    @mohamedyoussef8835 8 месяцев назад +1

    Awesome video +++++++++++++ 🙂

  • @mohsenmostafavi5028
    @mohsenmostafavi5028 9 месяцев назад +1

    Awesome man
    Do you have any plan for react course???

    • @ByteGrad
      @ByteGrad  9 месяцев назад

      Yes, it’s almost finished. Make sure you’re on the email list :)

  • @dereksniper
    @dereksniper Месяц назад +1

    can we conditionally render using signals?

  • @MightyKingKala
    @MightyKingKala 10 месяцев назад +1

    great video!

  • @ThugLifeModafocah
    @ThugLifeModafocah 8 месяцев назад

    That's why I use !! to transform the thing in a boolean then I do the && and avoid the ternary.

  • @user-dj8de9yf8l
    @user-dj8de9yf8l 6 месяцев назад +1

    It happened to me xd, thanks for the tip

  • @jkcdarunday
    @jkcdarunday 9 месяцев назад +1

    imo the cleanest way to handle this would be to use null coalesce (??)

  • @JeanDidier
    @JeanDidier 10 месяцев назад +1

    If there was a way to smash the like button for this video a thousand times, I would have done it

    • @ByteGrad
      @ByteGrad  10 месяцев назад

      Haha appreciate it

  • @aymenbachiri-yh2hd
    @aymenbachiri-yh2hd 5 дней назад +1

    Thanks man

  • @austincodes
    @austincodes 3 месяца назад

    Ternaries in JSX are way overused. I prefer to break it down into a smaller component and use an early return inside of an if statement. Yes it creates more lines of code but the added readability is worth it

  • @coders_rant
    @coders_rant 10 месяцев назад +1

    I was struggling to understand and find these types of good practices. Your videos are a blessing. Can i suggest some topics i find hard to capture? myb you can share your insight

    • @ByteGrad
      @ByteGrad  10 месяцев назад +1

      Good to hear. Yes let me know

    • @coders_rant
      @coders_rant 10 месяцев назад +1

      @@ByteGrad thanks. On top of my head
      Code splitting in nextjs,
      how to optimize render for different vw,
      When should we must use styles instead of tailwind class.i heard dynamic rendering still has bug with tailwind classes

    • @ByteGrad
      @ByteGrad  10 месяцев назад +1

      Good ideas, thanks

  • @holycow6935
    @holycow6935 10 месяцев назад +1

    Cant we use {productsInStock && "Products in stock"} ?

    • @ByteGrad
      @ByteGrad  10 месяцев назад

      An empty array is truthy. So if the array is empty we would then show "Products in stock".

    • @holycow6935
      @holycow6935 9 месяцев назад

      @@ByteGrad ahh intresting, thanks for insight!

  • @pasokoner
    @pasokoner 9 месяцев назад +1

    man that 0 value in jsx f*ck me up so many times.

  • @MrBl0m
    @MrBl0m 9 месяцев назад +1

    in web this will render 0 as you say but in react native it crash the app so its kind of a big deal to do this correct

    • @ByteGrad
      @ByteGrad  9 месяцев назад

      Great point

  • @KarthiKesavanS
    @KarthiKesavanS 10 месяцев назад +1

    You can increase your voice little bit, because I need to keep full volume in my Mac

    • @ByteGrad
      @ByteGrad  10 месяцев назад

      Thanks, will do. Didn’t realize volume was so low

  • @abdikadirQulle
    @abdikadirQulle 10 месяцев назад +3

    Thnk

  • @lighty262
    @lighty262 9 месяцев назад +1

    Here's what I used to do for rendering with condition
    {!condition || return}

  • @bakowicz4909
    @bakowicz4909 8 месяцев назад

    Mr. Clenched Jaw

  • @proplayer2472
    @proplayer2472 9 месяцев назад +1

    i usually just negate or double negate the condition just to be sure

  • @dealloc
    @dealloc 9 месяцев назад

    JSX does not define how logical operators work-this is pure JavaScript due to it being able to use non-boolean values as conditionals. JSX just considers null, undefined and false as "holes" in the JSX tree. The reason this doesn't apply for strings, and numbers (incl. NaN) is because otherwise you couldn't render those in normal circumstances.

  • @bartek...
    @bartek... 10 месяцев назад +1

    (I'm starting writing this comment with start of the video)
    And that's why I don't like loosely-type langs. I was love them, as a beginner. You can do so much 'smart' code that will abuse truthy and falsy values.
    If you need to use non boolean, you can Bang Bang in front or it, or convert it in less hipster way to boolean, but after all you should face logic for boolean only with booleans!
    I got dev fellow that whas always doing `if(myVar === undefined) doThis(); if(myVar === null) doThat(); if(myVar === 0) doThose()` just to protect himself from those scenarios.
    Binary world is way simpler, we don't need quantum physics with alternate timelines to compose whole universe from here's and now's.
    Good take though. Many people and developers (yes this days, not all dev's are people 🙀) are not aware of it. No one is starting from assembly any more?

    • @ByteGrad
      @ByteGrad  10 месяцев назад +1

      Good points

  • @user-in9fz5yc3o
    @user-in9fz5yc3o 9 месяцев назад

    Hii😊😊

  • @TheIpicon
    @TheIpicon 10 месяцев назад +1

    it does show the "", but it's just empty string... so it shows... an empty string

    • @ByteGrad
      @ByteGrad  10 месяцев назад

      Good point

  • @dubble_cuppachino
    @dubble_cuppachino 9 месяцев назад +2

    Plot twist: !!list.length && …

  • @vikrambhadoriya8830
    @vikrambhadoriya8830 6 месяцев назад

    Why not use "??"

  • @multiwebinc
    @multiwebinc 10 месяцев назад +3

    1:42 "This is not actually a JavaScript issue, it's actually a JSX issue" - Actually, that's incorrect. This is purely a Javascript behavior. Unlike other languages where && and || return booleans, in Javascript && returns either the first falsy variable, and if none are found, the last truthy variable. || returns either the first truthy variable, and if none are found, the last falsy variable. 0 is falsey, so that's why it returns 0 and it is therefore outputted to the page.

  • @ssong5557
    @ssong5557 8 месяцев назад +2

    I always don't like conditional rendering, not elegant

  • @itsorcus649
    @itsorcus649 9 месяцев назад

    is this me or his videos are helpful but hell lot boring

  • @ahmetnishefci4006
    @ahmetnishefci4006 9 месяцев назад

    I saw the thumbnail, didnt even bother to watch the video. And operator is better when u want to return null if the condition isnt met. Period!