Home > Blockchain >  React: Advantages for conditionals to check the negative before the affirmative?
React: Advantages for conditionals to check the negative before the affirmative?

Time:01-01

In Javascript, it seems like a general practice for an if statement to check if a favorable condition is met first,

e.g. a parameter or variable is presently defined and available for consumption:

const funcName = (necessaryParam) => {
  if (necessarryParam.length > 0) {
    console.log('condition met!');
    return; 
  }
console.log('condition not met!');
return;
}

In React, I see opportunities for positive-affirmation conditionals to skip an entire return statement:

const Component = (props) => {
  if (props)
  return (
    <YourComponent withProps={props} />
  )
}

to components that require parsing through several lines of code before saying they don't have enough information to function optimally:

function YourComponent(props) {
  return (
    { props && (
        <ComponentEveryoneWantsThatNeedsProps withProps={props} />
      )
    }
    { !props && (
        <ComponentThatTellsYouYoureScrewed />
      )
   )
}

In that general context, if I have a more sizeable part of a component that will render in the condition of the affirmative, compared to a smaller part rendering in the condition of the negative, should I check to see if the affirmative condition is not met before React parses the larger affirmative-condition codeblock? (Is this considered "good practice"?)

e.g. it's easier to check if you DON'T have what I need, because I can tell you to bugger off sooner...:

function ConditionallyRenderedComponent(props) {
  return (
    { !props && (
      <div>
        <OneComponent />
      </div>
      )
    } // vs
    { props && (
      <div>
        <FirstComponent>
         <H1>
          <SecondComponent />
         </H1>
        </FirstComponent>
      </div>
      )
    }
  )
}

Obviously these are extremely contrived examples, but hopefully my question makes sense.

Is there an argument for exposing only the simplest thing first? Is there a particular way to do it that you find works best?

Does it really even matter?

Any interesting or helpful material you've picked up regarding structuring conditionals in React you'd like to share?

CodePudding user response:

There are multiple considerations for ordering of conditional checks. Some examples:

Performance optimizations: e.g. filtering invalid inputs:

function calculateValue (...inputs) {
  if (!inputs.every(n => typeof n === 'number')) return NaN;
  // ...computationally expensive logic
  return expensiveResult;
}

Throwing an exception at an impasse to ensure that continuation only occurs with a valid state:

function findNestedSiblings () {
  // ...
  const element = document.querySelector(/* selector */);
  if (!element) throw new Error('msg');

  // element exists
  // continue...
}

Beyond performance optimizations, sometimes the structuring of conditionals can help with code readability (this begins to enter the territory of opinion). If you can handle a terminal condition first, (e.g. one resulting in return, throw, break, continue, yield, etc.), you often don't need an else block and can maintain your code at top-level indentation in the scope: I find this very useful and often aligned with the performance ordering.

  • Related